【问题标题】:how to reduce bar gap of stacked bar plot in ggplot2如何减少ggplot2中堆积条形图的条形间隙
【发布时间】:2015-05-11 13:52:47
【问题描述】:

我想减少条形间隙并保持堆叠条形图的条形宽度。

堆积条形图:

p <- ggplot(dat, aes(x = plant, y = percentage*100, fill = group)) + 
  geom_bar(stat = "identity", width =0.20)

然后我想通过position=position_dodge(0.9)更改条形间隙:

p <- ggplot(dat, aes(x = plant, y = percentage*100, fill = group)) + 
  geom_bar(stat = "identity", position=position_dodge(0.9),width =0.20)

此解决方案可以更改条形间距,但条形没有堆叠。那么如何改变条形间隙并保持条形宽度和堆叠?提前谢谢!

我的数据:

structure(list(plant = structure(c(1L, 1L, 1L, 1L, 1L, 2L), .Label = c("Cucumber-1", 
"Cucumber-2", "Eggplant-1", "Eggplant-2", "Pepper-1", "Pepper-2"
), class = "factor"), group = structure(c(1L, 2L, 3L, 4L, 5L, 
1L), .Label = c("[3.19e-39,2]", "(2,4]", "(4,6]", "(6,8]", "(8,10]"
), class = "factor"), n = c(14729L, 1670L, 447L, 131L, 16L, 20206L
), percentage = c(0.866768669452127, 0.0982757606073089, 0.0263049490966869, 
0.00770905667039369, 0.000941564173483199, 0.941039493293592)), .Names = c("plant", 
"group", "n", "percentage"), class = c("grouped_df", "tbl_df", 
"tbl", "data.frame"), row.names = c(NA, -6L), vars = list(plant), drop = TRUE, indices = list(
    0:4, 5L), group_sizes = c(5L, 1L), biggest_group_size = 5L, labels = structure(list(
    plant = structure(1:2, .Label = c("Cucumber-1", "Cucumber-2", 
    "Eggplant-1", "Eggplant-2", "Pepper-1", "Pepper-2"), class = "factor")), class = "data.frame", row.names = c(NA, 
-2L), .Names = "plant", vars = list(plant)))

【问题讨论】:

  • 删除position = position_dodge 它会导致条并排显示。一个简单的例子可能有助于澄清你的问题。
  • 您好,感谢您的快速回复。我已经更新了我的帖子,问题应该更清楚了。
  • @LJW 我以前读过这篇文章,但解决方案无法解决我的问题。
  • @LJW 首先,条形图应该是堆叠条形图(堆叠百分比条形图),然后我想保持条形宽度不变。最后,让堆叠的条更靠近彼此,但不要并排。

标签: r ggplot2 bar-chart


【解决方案1】:

position = position_dodge 用于并排显示条形图的填充部分。我无法特别找到解决此问题的方法。但是,当我遇到这样的问题时,我会调整整个图形的宽度以调整条形的宽度。考虑以下示例并查看调整宽度时保存的图表。希望这可以帮助。关键是,如果您将条形宽度变窄并减小条形之间的间距,最终您的图形宽度会减小。

ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar()
ggsave(filename = "trial1.png",plot = P,width=15,height = 10)

ggsave(filename = "trial2.png",plot = P,width=5,height = 10)

【讨论】:

  • 感谢您的解决方案。该解决方案应该是有帮助的,但不是那么优雅。很难将条形宽度、条形间隙和绘图宽度调整为和谐。
猜你喜欢
  • 1970-01-01
  • 2019-01-14
  • 1970-01-01
  • 2021-10-16
  • 1970-01-01
  • 1970-01-01
  • 2022-01-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多