gpt4 book ai didi

r - 用分段分布覆盖整体分布图

转载 作者:行者123 更新时间:2023-12-04 09:40:16 25 4
gpt4 key购买 nike

library(ggplot2)
library(data.table)

age = sample(1:100,100,T)
segment = sample(1:5,100,T)

data = data.frame(age,segment)

setDT(data)[age > 0 & age < 20, agegroup := "0-19"]

data[age >19 & age <40, agegroup := "20-39"]
data[age >39 & age <60, agegroup := "40-59"]
data[age >59, agegroup := "60+"]

我想代表整体和分割市场的年龄分布。

enter image description here

虚线是整体分布和每个分割市场,以便我可以比较分割市场和整体分布情况。如何在一张图中叠加两个图?

最佳答案

您必须为整体分布创建额外的数据集,合并它们并用不同的 geom_bar 绘图。的。

library(ggplot2) 
library(data.table)

# Using OPs data
data <- data[, .N, .(segment, agegroup)]
data2 <- data[, sum(N), .(agegroup)]
data3 <- merge(data, data2)


data3 <- merge(data3, data3[, .(MAX = max(N)), segment], "segment")

ggplot(data3, aes(agegroup)) +
geom_bar(aes(y = V1),
stat = "identity", position = "dodge",
color = "black", fill = "white",
linetype = 2) +
geom_bar(aes(y = N, fill = N == MAX),
stat = "identity", position = "dodge",
width = 0.6, color = "black") +
facet_wrap(~ segment) +
labs(x = "Age group",
y = "Number of observations") +
theme_bw() +
scale_fill_manual(values = c("grey", "grey5")) +
theme(legend.position = "none")

enter image description here

关于r - 用分段分布覆盖整体分布图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46796372/

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