【问题标题】:Combining position_dodge and position_fill in ggplot2在ggplot2中结合position_dodge和position_fill
【发布时间】: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" 绘制它。

标签: r ggplot2 bar-chart


【解决方案1】:

扩展我的评论:

library(ggplot2)
library(dplyr) 
library(tidyr)
library(scales)

df1 <- df %>%
    group_by(Month) %>%
    summarise(Value1 = sum(Value == 1) / n(),
              Value2 = sum(Value == 2) / n()) %>%
    gather(key = Group,value = Val,Value1:Value2)

df.plot2 <- ggplot(df1, aes(x = as.factor(Month),
                            y = Val, 
                            fill = as.factor(Group))) + 
    geom_bar(position = "dodge",stat = "identity") + 
    scale_y_continuous(labels = percent_format()) +
    scale_x_discrete(breaks = 1:12) + 
    labs(x = "Month", y = "Value")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多