在ggplot2中合并position_dodge和position_fill [英] Combining position_dodge and position_fill in ggplot2

查看:414
本文介绍了在ggplot2中合并position_dodge和position_fill的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的是同时使用 position =fill position =dodge参数 geom_bar()同时以某种方式。使用一些样本数据

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

酒吧在我想要的位置和缩放比例,但y轴标签代表了每个小节相对于总计数的百分比,而不是每个月的计数。

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?

推荐答案

展开我的评论:

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

这篇关于在ggplot2中合并position_dodge和position_fill的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆