Reputation: 51
This is my first post on Stack Overflow, my first reproducible example, and I'm new to R, so please be gentle! I am trying to display two histograms on one plot. Each histogram is a different variable (column) in my dataframe. I can't figure out how to both colour in the bars and have the legend displayed. If I use scale_fill_manual the colours are ignored, but if I use scale_colour_manual the colours are just the outlines of the bars. If I map the colours to each histogram separately (and don't use scale_xxx_manual at all) the colours work great but I then don't get the legend.
Here is my code:
TwoHistos <- ggplot (cars) +
labs(color="Variable name",x="XX",y="Count")+
geom_histogram(aes(x=speed, color= "Speed"), alpha = 0.2 ) +
geom_histogram(aes(x=dist, color= "Dist"), alpha = 0.2) +
scale_colour_manual(values = c("yellow","green"))
TwoHistos
Here is my result in an image (I pasted it but I don't know why it isn't showing up. I'm sorry!): Two histograms with outlines for colours
Upvotes: 5
Views: 2286
Reputation: 542
I think (if I understand you correctly), what you might want is to give a fill
arguement within the geom_histogram()
call.
(I've used the mtcars
built-in R data here as you did not give any data to work with)
TwoHistos <- ggplot (mtcars) +
labs(fill="Variable name",x="XX",y="Count")+
geom_histogram(aes(x=hp, fill= "Speed", color = "yellow"), alpha = 0.2 ) +
geom_histogram(aes(x=disp, fill= "Dist", color = "green"), alpha = 0.2) +
scale_fill_manual(values = c("yellow","green"))+
scale_colour_manual(values = c("yellow","green"), guide=FALSE)
TwoHistos
Edit: just to make really clear that I've changed the x
in the geom_histogram()
so it works with mtcars
Upvotes: 1
Reputation: 79311
Use fill
instead of color
and use scale_fill_manual
TwoHistos <- ggplot (cars) +
labs(color="Variable name",x="XX",y="Count")+
geom_histogram(aes(x=speed, fill= "Speed"), alpha = 0.2 ) +
geom_histogram(aes(x=dist, fill= "Dist"), alpha = 0.2) +
scale_fill_manual(values = c("yellow","green"))
TwoHistos
Upvotes: 1