gpt4 book ai didi

r - 使用 ggplot2 绘制比例频率,但省略了某些类别的数据

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

我正在尝试创建一个具有成比例频率的 ggplot。这是一个可重现的情节:

aa <- rep(c("Sta 1", "Sta 2", "Sta 3", "Sta 4"), each = 4)
bb <- rep(c("none", "minimal", "moderate", "major"), 4)
cc <- sample(1:40, 16, replace=F)

df <- data.frame(aa,bb,cc)


library(ggplot2)

cols <- c("none" = "light green", "minimal" = "dark green", "moderate" = "light blue", "major" = "dark blue")

plot <- ggplot(df, aes(fill=bb, y = cc, x = aa))
plot + geom_bar(position = "fill", stat = "identity") + scale_colour_manual(values = cols, aesthetics = c("colour", "fill"))
我被要求省略“无”和“最小”类别,但仍包括整体比例。我有一个解决方法,可以使用 NA 将类别颜色设置为透明:
cols <- c("none" = NA, "minimal" = NA, "moderate" = "light blue", "major" = "dark blue")
我对此并不那么有经验,但想知道是否有更优雅的解决方案来忽略大块数据?

最佳答案

尝试这个:

library(ggplot2)

cols <- c("none" = "light green", "minimal" = "dark green", "moderate" = "light blue", "major" = "dark blue")

plot <- ggplot(df, aes(fill=bb, y = cc, x = aa))
plot + geom_bar(position = "fill", stat = "identity") +
scale_colour_manual(values = cols, aesthetics = c("colour", "fill"),
breaks=c('moderate','major'))
输出:
enter image description here
一种选择可以是:
#Code 2
plot <- ggplot(subset(df,!bb %in% c("none","minimal")), aes(fill=bb, y = cc, x = aa))
plot + geom_bar(position = "fill", stat = "identity") + scale_colour_manual(values = cols, aesthetics = c("colour", "fill"))
输出:
enter image description here
或者这个选项:
#Code 3
plot <- ggplot(df, aes(fill=bb, y = cc, x = aa))
plot + geom_bar(position = "fill", stat = "identity") +
scale_colour_manual(values = cols, aesthetics = c("colour", "fill"),
breaks=c('moderate','major'),
limits=c('moderate','major'))
输出:
enter image description here

关于r - 使用 ggplot2 绘制比例频率,但省略了某些类别的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65671525/

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