简体   繁体   中英

Combining position_dodge and position_fill in ggplot2

What I would like to do is use both the position = "fill" and the position = "dodge" arguments of geom_bar() at the same time somehow. Using some sample data

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

I'm able to create the following graph

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

在此输入图像描述

I like the scaling and labeling of this graph but I want to be able to unstack it. However when I do the following

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

在此输入图像描述

The bars are in the position and scaling that I want but the y-axis labels represent the percentage of each bar relative to the total count, not the count within each month.

All in all I want the visuals of the second graph with the labeling of the first graph. Is there a relatively easy way to automate this?

Expanding on my comment:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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