gpt4 book ai didi

r - 在 ggplot2 中结合 position_dodge 和 position_fill

转载 作者:行者123 更新时间:2023-12-03 21:50:25 27 4
gpt4 key购买 nike

我想做的是同时使用 position = "fill"position = "dodge" geom_bar() 的参数同时不知何故。使用一些样本数据

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

enter image description here

我喜欢这个图的缩放和标签,但我希望能够将它拆开。但是,当我执行以下操作时
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")

enter image description here

条形位于我想要的位置和缩放比例,但 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")

关于r - 在 ggplot2 中结合 position_dodge 和 position_fill,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36087904/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com