简体   繁体   English

如何将图例添加到 ggplot 多个 geom_bar

[英]How to add legend to ggplot multiple geom_bar

I have a code like this我有这样的代码

# two data frames
sf =  data.frame(days = c('05-06', '05,08'), Frequency = c(0, 2))
normal = data.frame(days = c('05-06', '05,07'), Frequency = c(1, 3))

# plot
ggplot() + 
  geom_bar(aes(y = Frequency, x = days), data = normal, 
           stat="identity", colour = 'black') +
  geom_bar(aes(y = Frequency, x = days), data = sf, 
           stat="identity", colour = 'red')

I want to add legend to it with red and black color, I tried this one which is the most related solution to my question, but it just shows the legend for the first barplot.我想传说添加到它有红色和黑色,我想这一个是最相关的解决我的问题,但它只是显示了第一barplot的传说。 How can I have a barplot legend with black and red color?我怎样才能有一个黑色和红色的条形图图例?

Notice: it is not one data frame, they are two separate data frames, with different number of rows, so I can not merge them together.注意:它不是一个数据框,它们是两个独立的数据框,行数不同,所以我无法将它们合并在一起。 So I plot two bar plots.所以我绘制了两个条形图。 The above code fill the plots, what I want is to add a legend that shows the first bar plot is black and the second one is red.上面的代码填充图,我想要的是添加一个图例,显示第一个条形图是黑色的,第二个是红色的。

As with many ggplot questions, the problem you are facing stems from the data not being in the correct format.与许多 ggplot 问题一样,您面临的问题源于数据格式不正确。 You should have a single dataframe, with the columns days , Frequency and group .您应该有一个数据框,其中包含daysFrequencygroup列。

Set the colour within the aesthetic group of the ggplot, and then specify an manual colour scale to set the colours and black.在ggplot的审美组内设置颜色,然后指定手动色标来设置颜色和黑色。

library(ggplot2)

df =  data.frame(days = c('05-06', '05,08', '05-06', '05,07'),
                 Frequency = c(0, 2, 1, 3),
                 group = c("sf", "sf", "normal", "normal"))


# plot
ggplot(df, aes(y = Frequency, x = days, fill = group)) + 
  geom_bar(stat="identity") +
  scale_fill_manual(values = c("red", "black"))

在此处输入图片说明

I would encourage reading the basics of ggplot reference guidance to get a bit more of an understanding about how to use the data: http://ggplot2.tidyverse.org/reference/ .我鼓励阅读 ggplot 参考指南的基础知识,以对如何使用数据有更多的了解: http : //ggplot2.tidyverse.org/reference/ In addition, the ggplot cheatsheet is a useful reference: https://www.rstudio.com/wp-content/uploads/2015/03/ggplot2-cheatsheet.pdf此外,ggplot 备忘单是一个有用的参考: https ://www.rstudio.com/wp-content/uploads/2015/03/ggplot2-cheatsheet.pdf

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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