gpt4 book ai didi

r - 使用ggplot在多个条形图中添加组信息

转载 作者:行者123 更新时间:2023-12-05 02:26:13 25 4
gpt4 key购买 nike

假设我有下面的多个条形图和 ggplot

raw <- read.csv("http://pastebin.com/raw.php?i=L8cEKcxS",sep=",")
raw[,2]<-factor(raw[,2],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,3]<-factor(raw[,3],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,4]<-factor(raw[,4],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)

raw=raw[,c(2,3,4)]

freq=table(col(raw), as.matrix(raw)) # get the counts of each factor level
Names=c("Food","Music","People")
data=data.frame(cbind(freq),Names)
data=data[,c(5,3,1,2,4)]


data.m <- melt(data, id.vars='Names')


ggplot(data.m, aes(Names, value)) +
geom_bar(aes(fill = variable), position = "dodge", stat="identity")

这很好。不过,我想沿 x 轴 添加一些组信息。假设 2 个组被定义为 Group1:食物和音乐Group2:人。有了这个,我正在尝试构建一个 ggplot 如下所示

enter image description here

我还想减少 Food & Music 之间的空间并增加 Music & People 之间的空间 - 只是为了演示 Food & Music组成 1 组和 People 另一组。

有什么方法可以使用 ggplot 框架实现这一点?

最佳答案

有几个选项,例如将组信息作为注释添加到您的绘图中。但恕我直言,一个好的起点和最简单的方法是使用分面:

使用一些假的示例数据:

library(ggplot2)

variable <- c("Very Bad","Bad","Good","Very Good")

data.m <- data.frame(
Names = rep(c("Food","Music","People"), each = 4),
value = 1:12,
variable = factor(variable, levels = variable)
)
data.m$group <- ifelse(data.m$Names %in% c("Food", "Music"), "Group 1", "Group 2")

ggplot(data.m, aes(Names, value)) +
geom_bar(aes(fill = variable), position = "dodge", stat="identity") +
facet_grid(.~group, space = "free", scales = "free_x", switch = "x") +
theme(strip.placement = "outside",
strip.background.x = element_rect(fill = NA),
strip.text.x = element_text(color = "red"))

关于r - 使用ggplot在多个条形图中添加组信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74011753/

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