简体   繁体   中英

How to plot two histograms of different variables in one GGPlot, with legend and colours

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

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 在此处输入图像描述

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

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM