繁体   English   中英

在 R (ggplot2) 中将分组条形图居中

[英]Center a grouped bar chart in R (ggplot2)

因此,我正在制作一个关于年龄组中原有疾病患病率的组条形图。 不出所料,年轻人没有像老年人那样多的条件,所以有些群体是 0。

PreEx <- c("Cardiovascular Disease", "Lung Disease", "Diabetes", "Hypertension", 
           "Renal Disease", "Autoimmune/Endocrine/Metabolic Disease", 
           "Neurological/Psychiatric Illness", "Other Disease")

PreBar <- data.frame(Freq=c(0 ,0 , 0, 0, 0, 0, 0, 9.1, 0, 3.4, 0, 0, 0, 0, 1.7, 
                            0, 3.4, 4.3, 3.9, 3, 0.8, 1.4, 1.3, 1.6, 14.2, 3.1, 
                            17, 8, 1.7, 4.5, 1.7, 2.8, 30.6, 9.9, 25.2, 13.5, 
                            4.5, 6.3, 1.8, 3.6),
                     Age=c(rep("0-4 yrs", 8), rep("5-17 yrs", 8), rep("18-49 yrs", 8), 
                           rep("50-64 yrs", 8), rep("65+ yrs", 8)), 
                     PreCond= rep(PreEx, 5))

问题是,条形图保持它们的位置,就好像 0 的值在那里一样。 这使图表看起来像条不居中。 我附上了一张图表目前的样子。

在此处输入图像描述

我也无法删除零值,因为条形不是等效宽度。

在此处输入图像描述

这是 plot 代码的样子(我确实取出了我正在使用的特定配色方案)。

library(ggplot2)
ggplot(data=PreBar, aes(x=Age, y=Freq, fill=PreCond)) +
  geom_bar(position="dodge", stat="identity") +
  theme_light() +
  ylab("Percentage of Pre-existing Condition Among Positives") +
  xlab("Age Category") 

在保持所有条形宽度相同的同时,将每个分组条形集居中的最简单方法是什么?

最简单的解决方案是使用position_dodge2()preserve=参数。 正如您所观察到的,当您删除“0”值时,条形的宽度不相等。 这是 position_dodge2() 的preserve=参数背后的原理,也就是说,应该在每个 x 值( "total" )中保留条形的宽度还是在所有 x 值( "single" ”)中保留所有条形的宽度"single" )? 第二个是你想要的。

position_dodge()position_dodge2()有什么区别? 好吧, position_dodge()有效,但不会将分组集中在 x 值上(您的原始问题)。 position_dodge2()就是这样做的:

PreBar <- PreBar[which(PreBar$Freq!=0),]  # remove your zeros

library(ggplot2)
ggplot(data=PreBar, aes(x=Age, y=Freq, fill=PreCond)) +
  geom_bar(position=position_dodge2(preserve='single'), stat="identity") +
  theme_light() +
  ylab("Percentage of Pre-existing Condition Among Positives") +
  xlab("Age Category") 

在此处输入图像描述

您可以使用带有自由鳞片的刻面来实现效果。 (我并不是说效果一定是一个好主意,正如其他评论所指出的那样,但可以做到。)

ggplot(subset(PreBar, Freq > 0),
       aes(x = PreCond, y = Freq, fill = PreCond)) +
  geom_col() +
  facet_grid(~Age, space = "free_x", scales = "free_x", switch = "x") +
  theme_light() +
  theme(axis.text.x = element_blank(), 
        axis.ticks.x = element_blank(),
        panel.spacing = unit(0, "pt"),
        panel.border = element_blank(),
        panel.grid.major.x = element_blank(),
        strip.background = element_blank(),
        strip.text = element_text(colour = "black"))  +
  scale_x_discrete(name = "Age Category",
                   expand = c(0, 1)) +
  ylab("Percentage of Pre-existing Condition Among Positives") +
  scale_fill_brewer(palette = "RdYlBu")

阴谋

暂无
暂无

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

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