how to reduce bar gap of stacked bar plot in ggplot2

做~自己de王妃 提交于 2020-01-05 17:57:13

问题


I would like to reduce bar gap and keep bar width of stacked bar plot.

Stacked bar plot:

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

and then I want to change bar gaps by 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)

This solution can change bar gaps, but bars were unstacked. So how to change bar gap and keep bar width and stacked? Thank you in advance!

My data:

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

回答1:


position = position_dodge is used to show the fill part of bar graphs side by side. I cannot particularly find a solution to this. However, when I face such problem, I adjust the width of the entire graph to adjust width of the bars. Consider the following example and see the graphs that are saved when you adjust the width. Hope this helps. The point is if you make the bar width narrower and decrease the space between the bars, ultimately your graph width decreases.

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)



来源:https://stackoverflow.com/questions/30159962/how-to-reduce-bar-gap-of-stacked-bar-plot-in-ggplot2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!