【问题标题】:bar plot with two seperate bars of df with multiple values具有多个值的 df 的两个单独条形的条形图
【发布时间】:2020-01-23 16:12:31
【问题描述】:

以下问题: 我有这个数据集

df
Ch         V1          V2
A          a1          a2
B          b1          b2
C          c1          c2
....

而 V1 和 V2 是数值。我想为每个 V1 和 V2 值创建一个带有条形图的条形图。 我试过的代码

ggplot(data = df %>% gather(Variable, No., -Ch), 
       aes(x = reorder(ID,-No.), y = No., fill = Variable)) + 
  geom_bar(stat = 'identity', position= position_dodge())+
  geom_col()+
  xlab("Section of industry")+
  ylab("No. of occurences")+
  theme_classic()+
  theme(axis.text.x = element_text(angle = 45, size=1),
        plot.title = element_text(hjust = 0.5),
        legend.position = "top")+
  ggtitle("XXX")

即使使用 position= position_dodge() 它也只会像这样将两个条合并为一个: 知道如何分离或为什么 positon_dodge() 不起作用?我想是因为我以前用过聚集功能?

另一个问题是,Ch 的值太大,所以如果我想以可读的方式显示它们,图形就会“消失”。有没有办法显示这些值(可能将值写成两行)以便显示?

非常感谢!

【问题讨论】:

    标签: r dataframe ggplot2


    【解决方案1】:

    您的问题是您的ggplot 调用中同时具有geom_bargeom_col,因此geom_bar 中的position_dodge() 参数被geom_col 超越,从而产生了一个堆叠条。因此,删除 geom_col 应该可以。或者,您可以删除geom_bar 并将position = position_dodge() 传递给geom_col

    要缩写您的 x 标签,您可以使用scale_x_discrete(abbreviate),如本文所述:How can I shorten x-axis label text in ggplot?

    library(dplyr)
    library(ggplot2)
    library(tidyr)
    df %>% pivot_longer(.,-Ch, names_to = "Var", values_to = "Val") %>%
      ggplot(aes(x = Ch, y = Val, fill = Var))+
      geom_col(position = position_dodge())+
      xlab("Section of industry")+
      ylab("No. of occurences")+
      theme_classic()+
      theme(axis.text.x = element_text(angle = 45, hjust = 1),
            plot.title = element_text(hjust = 0.5),
            legend.position = "top")+
      ggtitle("XXX")+
      scale_x_discrete(label = abbreviate)
    

    示例数据

    structure(list(Ch = structure(1:5, .Label = c("AAAAAAAAAAAAAA", 
    "BBBBBBBBBBBB", "CCCCCCCCCCCCCCCC", "DDDDDDDDDDDDDD", "EEEEEEEEEEEEE"
    ), class = "factor"), V1 = 1:5, V2 = 5:9), class = "data.frame", row.names = c(NA, 
    -5L))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-28
      • 1970-01-01
      • 2014-08-02
      • 2020-09-18
      • 2021-06-27
      • 2017-09-06
      • 1970-01-01
      相关资源
      最近更新 更多