geom_bar中的条宽度不相等 [英] Bars in geom_bar are not of equal width
问题描述
对于下面的数据框,我想用 ggplot
来制作几个柱状图。
For the following data frame I want to make several bar plots using ggplot
.
df <- data.frame(Disease = c("Disease1","Disease2","Disease3","Disease3","Disease3","Disease4","Disease5","Disease5","Disease6","Disease4","Disease2","Disease2","Disease1","Disease7","Disease1","Disease1","Disease7","Disease6","Disease3","Disease6"),
Week = c(3,52,46,47,19,39,42,46,44,45,46,42,45,48,44,44,43,42,45,47),
Year = c(2015,2015,2015,2016,2015,2015,2016,2016,2015,2015,2015,2015,2016,2016,2016,2015,2016,2016,2016,2015),
Number = c(1,1,6,5,1,1,4,12,4,15,6,15,6,11,4,2,9,1,4,1))
我使用以下语法我的几个柱状图。
I use the following syntax which gives me several bar plots.
ggplot(df, 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")
然而,我想所有的酒吧都有相同的宽度(关于宽度的差异,请参阅疾病1)。我已经在这里找到了答案酒吧在使用facet_wrap时,在geom_bar中有不需要的不同宽度,但我无法在我的示例中获得此功能。有没有人有解决我的问题?
显然,我的原始数据集要大得多,而且不同条形宽度的问题比我上面的示例中出现的频率要高得多。
However, I would like all bars to have the same width (see Disease 1 for differences in width). I have already found an answer here Bars in geom_bar have unwanted different widths when using facet_wrap but I cannot get this to work in my example. Does anyone have a solution to my problem? Obviously, my original dataset is much larger and the problem of different bar widths occurs much more often than in my example above.
推荐答案
您可以通过为每个疾病+周+年填充数据集来解决此问题:
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")
您也可以尝试填充0.1这样的小数字,以便在每个x轴位置获得一些小条 - 我认为这可以帮助明确存在每个酒吧都有一个空间,但是您引入了可能令人困惑的假值:
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))
这篇关于geom_bar中的条宽度不相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!