【发布时间】:2016-03-18 15:10:44
【问题描述】:
我想做的是以某种方式同时使用geom_bar() 的position = "fill" 和position = "dodge" 参数。使用一些样本数据
set.seed(1234)
df <- data.frame(
Id = rep(1:10, each = 12),
Month = rep(1:12, times = 10),
Value = sample(1:2, 10 * 12, replace = TRUE)
)
我可以创建以下图表
df.plot <- ggplot(df, aes(x = as.factor(Month), fill = as.factor(Value))) +
geom_bar(position = "fill") +
scale_x_discrete(breaks = 1:12) +
scale_y_continuous(labels = percent) +
labs(x = "Month", y = "Value")
我喜欢这张图的缩放和标签,但我希望能够将它拆开。但是,当我执行以下操作时
df.plot2 <- ggplot(df, aes(x = as.factor(Month), fill = as.factor(Value))) +
geom_bar(position = "dodge", aes(y = (..count..)/sum(..count..))) +
scale_x_discrete(breaks = 1:12) +
scale_y_continuous(labels = percent) +
labs(x = "Month", y = "Value")
这些条位于我想要的位置和缩放比例,但 y 轴标签表示每个条相对于总计数的百分比,而不是每个月内的计数。
总而言之,我想要第二张图的视觉效果和第一张图的标签。有没有一种相对简单的方法可以实现自动化?
【问题讨论】:
-
与其试图强迫 ggplot 做一些它认为尴尬的事情,我通常会简单地按照我想要的方式预先聚合数据,然后使用
stat = "identity"绘制它。