【问题标题】:Grouped bar chart using ggplot使用 ggplot 分组条形图
【发布时间】:2017-02-02 17:17:08
【问题描述】:

我有以下数据框:

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 = "")

我想创建一个分组条形图。我使用了plotly,结果如我所愿:

但是,我意识到要以 eps 格式下载它,我必须付费订阅。出于这个原因,我尝试了ggplot。这是我尝试使用教程的方法:

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

结果不是我真正想要的:

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您需要将数据重塑为长格式,然后使用 ggplot。不要忘记将 stat 设置为 identity 并将 position 设置为“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)
    

    如果你想让它看起来有点像你的原版,你可以这样做:

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

    【讨论】:

      猜你喜欢
      • 2018-12-03
      • 1970-01-01
      • 1970-01-01
      • 2013-08-12
      • 1970-01-01
      • 1970-01-01
      • 2018-04-01
      • 1970-01-01
      相关资源
      最近更新 更多