条形图,带有两个具有多个值的df分隔条

时间:2020-01-23 16:12:31

标签: r dataframe ggplot2

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

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(),它也只能将两个条合并为一个: enter image description here 知道如何分隔或为什么positon_dodge()无法正常工作吗?我想是因为我以前使用过collect函数吗?

另一个问题是,Ch的值太大,因此如果我想以可读的方式显示它们,则图形“消失”。有没有办法显示这些值(也许将值写在两行中)以便可以显示出来?

非常感谢您!

1 个答案:

答案 0 :(得分:1)

您的问题是您在geom_bar调用中同时拥有geom_colggplot,因此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)

enter image description here

示例数据

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))
相关问题