r - 创建一个堆叠分组的条形图,每个条形图具有不同的类别?
问题描述
我有四个变量:类别、x、y 和 z。X 轴应该是类别,每个类别应该有两个条,第一个是 x 堆叠在 z 之上,第二个是 y 堆叠在 z 之上。它应该看起来像此处链接的图像(z 为蓝色):
sampledata <- data.frame(
categories = c("2017", "2018", "2019", "2020"),
x = c(2, 3, 0, 4),
y = c(0, 2, 1, 4),
z = c(1, 0 ,2 ,3)
)
解决方案
从技术上讲,没有办法在 geom_bar 中直接组合堆叠和闪避样式。但也许你可以做到这一点:
#Your data frame
sampledata <- data.frame(
categories = c("2017", "2018", "2019", "2020"),
x = c(2, 3, 0, 4),
y = c(0, 2, 1, 4),
z = c(1, 0 ,2 ,3)
)
#Reshape into tidy data
library(tidyverse)
sampledata2<-sampledata %>%
gather('x','y','z',key='variable',value='value')%>%
mutate(group=ifelse(variable=='y','b','a')) #group into 2 groups (xz and yz)
sampledata2[13:16,]<-sampledata2[9:12,]
sampledata2[13:16,4]<-c('b','b','b','b')
sampledataA<-sampledata2 %>%
filter(group=='a')
sampledataB<-sampledata2 %>%
filter(group=='b')
#plot
barwidth=0.30
ggplot()+
#geom_bar for x and z
geom_bar(data=sampledataA,
mapping=aes(fill=variable,y=value,x=categories),
position="stack",
stat="identity",
width=barwidth)+
#geom_bar for y and z
geom_bar(data=sampledataB,
mapping=aes(x=as.numeric(categories)+barwidth+0.1,fill=variable,y=value),
position="stack",
stat="identity",
width=barwidth)
如果它不起作用,请提供更多信息:https ://community.rstudio.com/t/ggplot-position-dodge-with-position-stack/16425
推荐阅读
- ios - iOS - 用作依赖项时协议和泛型出错
- java - 颤振医生 --android-licenses 给出一个 java 错误
- c# - 从更新面板内动态生成的按钮调用服务器端方法
- graphql - Postman,测试 Graphql 响应
- javascript - 为什么我的 FizzBuzz 代码没有正确输出?
- c++ - 在 C++ 中继承结构
- php - 为什么我在尝试查找特定用户时从 laravel 的数据库中获取空值?
- typescript - 将两种类型关联在一起
- tomcat - 从 Tomcat ExpiresFilter 缓存中排除特定 URL
- amazon-web-services - 如何防止 API Gateway OAuth 范围在 Lambda 函数部署时被重置?