简体   繁体   English

使用ggplot分组的条形图

[英]Grouped bar chart using ggplot

I have the following data frame: 我有以下数据框:

df<- read.table(text = "months ratio_1 ratio_2
1  January  11.757426       18.047800
2  February 12.515489       20.544807
3  March    12.703583       18.818962
4  April    11.348465       15.229768
5  May      13.366337       12.030971
6  June     15.371622       12.866768
7  July     13.157895        7.711387
8  August   12.939002       11.344097
9  September 8.401084       16.298587
10 October   10.494753       14.334838
11  November 8.695652       19.626384
12  December    11.248285       16.640037", header = TRUE, sep = "")

and I want to create a grouped bar chart. 我想创建一个分组的条形图。 I used plotly and the result is as I want to be: 我使用了plotly,结果如我所愿: 阴谋地

However, I realized that in order to download it as eps format, I have to pay a subscription. 但是,我意识到,要以eps格式下载它,必须支付订阅费用。 For that reason, I tried ggplot. 因此,我尝试了ggplot。 This is what I tried using the tutorials: 这是我尝试使用教程的内容:

  gplot(df, aes(months, ratio_1)) +   
  + geom_bar(aes(fill = ratio_2), position = "dodge", stat="identity")

The result is not what I actually want: 结果不是我真正想要的: ggplot

You need to reshape the data to a long format and then use ggplot. 您需要将数据重整形为长格式,然后使用ggplot。 Don't forget setting the stat to identity and the position to "dodge "("stacked" by default). 不要忘记将stat设置为identity,并将位置设置为“ dodge”(默认情况下为“ stacked”)。

library(ggplot2)
library(reshape
ggplot(melt(df,id.vars="months"),aes(x=months,y=value,fill=variable))+
  geom_bar(stat="identity",position="dodge")+
  theme_bw()+
  scale_fill_discrete(labels=c("Ratio 1","Ratio2"),name=NULL)

And if you want it to look somewhat like your original you could do: 如果您希望它看起来像您的原始作品,则可以执行以下操作:

ggplot(melt(df,id.vars="months"),aes(x=months,y=value,fill=variable))+
  geom_bar(stat="identity",position="dodge")+
  theme_bw()+
  scale_fill_manual(labels=c("ratio 1","ratio2"),name=NULL,values = c("blue", "orange"))+
  ylab("Percentage %")+
  xlab("Months")

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

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