ggplot中的多直方图中的图例不出现

时间:2020-10-04 23:30:38

标签: r ggplot2

我正在从3个随机生成的向量中生成一个直方图,然后生成一个将向量相连接的数据帧,并为每个向量添加一个键(“ a”,“ b”和“ c”),但图例未显示图。

SAg_exp = rexp(cenarios,1/lambda)
SAg_unif= runif(cenarios,0,1)
normal= rnorm(cenarios,0,1)
dat <- data.frame(xx = c(SAg_exp,SAg_unif,normal),yy = rep(letters[1:3],each = cenarios))
graph = ggplot(dat, aes(x=xx)) + 
  geom_histogram(data=subset(dat,yy == 'a'),fill = "red",aes(fill=yy),alpha = 0.2) +
  geom_histogram(data=subset(dat,yy == 'b'),fill = "blue",aes(fill=yy),alpha = 0.2) +
  geom_histogram(data=subset(dat,yy == 'c'),fill = "green",aes(fill=yy),alpha = 0.2) +
  ggtitle(paste("Histograma SAg:",tamanho,"apólices vs.",cenarios,"cenários")) + 
  ylab("Frequência") + xlab("SAg") +
  scale_fill_manual(name="yy",values=c("a","b","c"),labels=c("Exponencial","Uniforme","Normal"))
print(graph)

这是生成的图,但是没有图例。

enter image description here

有人可以帮助我吗?谢谢!

1 个答案:

答案 0 :(得分:1)

尝试这种方法。关键是使用aes()参数在fill周围玩耍。之后,像您一样使用scale_fill_manual()可以格式化图例中的颜色和标签。这里的代码对您的解决方案稍有更改:

library(ggplot2)
library(dplyr)
library(tidyr)
#Data
cenarios <- 100
lambda <- 0.8
SAg_exp = rexp(cenarios,1/lambda)
SAg_unif= runif(cenarios,0,1)
normal= rnorm(cenarios,0,1)
dat <- data.frame(xx = c(SAg_exp,SAg_unif,normal),yy = rep(letters[1:3],each = cenarios))
#Plot
graph <- ggplot(dat, aes(x=xx,group=yy,fill=yy)) +
  geom_histogram(data=subset(dat,yy == 'a'),aes(fill='a'),alpha = 0.2) +
  geom_histogram(data=subset(dat,yy == 'b'),aes(fill = "b"),alpha = 0.2) +
  geom_histogram(data=subset(dat,yy == 'c'),aes(fill="c"),alpha = 0.2) +
  ggtitle(paste("Histograma SAg:","apólices vs.",cenarios,"cenários")) + 
  ylab("Frequência") + xlab("SAg") +
  scale_fill_manual(name="yy",
                    labels=c("a"="Exponencial","b"="Uniforme","c"="Normal"),
                    values=c('red','blue','green'))

输出:

enter image description here

要更改图例中标题的名称,您可以像这样调整name中的scale_fill_manual()选项:

#Plot 2
graph <- ggplot(dat, aes(x=xx,group=yy,fill=yy)) +
  geom_histogram(data=subset(dat,yy == 'a'),aes(fill='a'),alpha = 0.2) +
  geom_histogram(data=subset(dat,yy == 'b'),aes(fill = "b"),alpha = 0.2) +
  geom_histogram(data=subset(dat,yy == 'c'),aes(fill="c"),alpha = 0.2) +
  ggtitle(paste("Histograma SAg:","apólices vs.",cenarios,"cenários")) + 
  ylab("Frequência") + xlab("SAg") +
  scale_fill_manual(name="Variable",
                    labels=c("a"="Exponencial","b"="Uniforme","c"="Normal"),
                    values=c('red','blue','green'))

输出:

enter image description here