0

I am generating a histogram from 3 randomly generated vectors and then I generate a dataframe concatenating the vectors and add a key for each one ("a", "b" and "c") but the legend is not shown in the graph.

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)

So here is the generated graph, but without a legend.

enter image description here

Can someone help me? Thank you!

1 Answers1

2

Try this approach. The key is playing around aes() with the fill argument. After that the use of scale_fill_manual() as you did allows formating the colors and labels in the legends. Here the code with slight changes to your solution:

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'))

Output:

enter image description here

In order to change the name of the title in legend you can adjust the name option in scale_fill_manual() like this:

#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'))

Output:

enter image description here

Duck
  • 39,058
  • 13
  • 42
  • 84