关于R中ggplot中的分组

问题描述

我有此数据框,我想将期望的栏与不同的患者个人数据分组。我编写了代码,但仅适用于1位患者。我想对14位患者进行此操作。如图所示,此图适用于1位患者,我必须为所有患者显示相似的组。目前,我有2位患者的数据。所以我必须标记14位患者的x轴,但将图保留为空

hand drawn

enter image description here

c<- data.frame(Var=character(),Expected=double(),Pat_1=double(),Pat_2=double(),stringsAsFactors=FALSE) 
x<-data.frame("IT-6",2,4,3)
names(x)<-c('Var','Expected','Pat_1','Pat_2')
c<-rbind(c,x)

x<-data.frame("IT-7",3,8)
names(x)<-c('Var',x)

x<-data.frame("IT-8",7)
names(x)<-c('Var',x)

c_melt<-melt(c,id = c("Var"))
c_melt<-dplyr::rename(c_melt,"Patient"="variable")
c_melt$col<-ifelse(grepl("Expected",c_melt$Patient),"gray88","grey60")

> c_melt
   Var  Patient value    col
1 IT-6 Expected     2 gray88
2 IT-7 Expected     3 gray88
3 IT-8 Expected     4 gray88
4 IT-6    Pat_1     4 grey60
5 IT-7    Pat_1     2 grey60
6 IT-8    Pat_1     2 grey60
7 IT-6    Pat_2     3 grey60
8 IT-7    Pat_2     8 grey60
9 IT-8    Pat_2     7 grey60


ggplot(data=c_melt,aes(x=Var,y=value,fill=col))+
  geom_bar(stat="identity",na.rm = T,position="dodge")+
  labs(y="display(%)",x="")+
  theme(axis.title.x = element_blank(),axis.text.x = element_text(size=12,angle=0,vjust = 0.5,face = c( 'bold')),panel.grid.major.x = element_blank(),panel.grid.minor.x = element_blank())+
  theme(axis.ticks=element_line(colour = "black"),panel.border =  element_rect(colour = "black",fill=NA,size=0.5),panel.background = element_blank(),axis.title.y  = element_text(size=15,vjust = 0.5),axis.text.y=element_text(size=12,vjust = 0.5))+
  theme(legend.position = "none")+ 
scale_fill_identity()

解决方法

也许您可以尝试facet_wrap

ggplot(data=c_melt,aes(x=Var,y=value,fill=col))+
  geom_bar(stat="identity",na.rm = T,position="dodge")+
  facet_wrap(~Patient) +
   
,

我认为您需要一个更好的例子来展示您的追求。

以下是一些想法,这些想法要么填充在“患者”上,要么在填充“患者”时在“患者”上分组。他们如何比较?

library(tidyverse)
library(tibble)

c_melt <- tibble( Var = c("IT-6","IT-7","IT-8","IT-6","IT-8"),Patient = c("Expected","Expected","Pat_1","Pat_2","Pat_2"),value = c(2,3,4,2,8,7),col = c("gray88","gray88","gray60","gray60")
                )

#Example 1
c_melt %>% 
ggplot(aes(x=Var,fill=Patient))+
  geom_bar(stat="identity",position="dodge") 


#Example 2
c_melt %>% 
ggplot(aes(x=Var,fill=col,group=Patient))+
  geom_bar(stat="identity",position="dodge") +
  scale_fill_identity() +
  theme_bw()

reprex package(v0.3.0)于2020-11-03创建