繁体   English   中英

将position_dodge和position_fill组合在ggplot2中

[英]Combining position_dodge and position_fill in ggplot2

我想做的是以某种方式同时使用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轴标签表示每个条形相对于总计数的百分比,而不是每个月内的计数。

总而言之,我希望第二个图形的视觉效果与第一个图形的标记。 是否有一种相对简单的自动化方法?

扩展我的评论:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM