Bars in geom_bar are not of equal width

孤者浪人 提交于 2019-12-02 07:18:23

You can fix this by filling out the dataset with a 0 for each Disease + Week + Year:

library(tidyverse)
df2 = df %>%
    complete(Disease, Week, Year, fill = list(Number = 0))

ggplot(df2, aes(factor(Week), Number )) + 
    geom_bar(stat="identity" , aes(fill = factor(Year)), position = "dodge") + 
    facet_wrap(~ Disease, ncol = 2, scales = "free_y") +
    labs(x = "Week", y = "Number") +
    scale_fill_discrete(name = "Year")

You could also try filling with a small number like 0.1 so you get some tiny bars at each x-axis location - I think this can help make clear that there is a space there for each bar, but you are introducing potentially confusing fake values:

df2 = df %>%
    complete(Disease, Week, Year, fill = list(Number = 0.1))

That's normal: on the x axis, every unit has the same space on the axis (here, 1 week).

There are weeks where there are just 2015, just 2016, none, or both. When there are both years, the week unit is the same as when there are just one year. So when there are both years to be plotted, the "space for a unit" is splitted in two, hence the bar which are twice smaller.

The "problem" is then not on the facet_wrap, but due to position = "dodge", which puts bar side to side.

Colin

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