如何将多个ggplot图与同一构面下的不同数据框组合在一起?

如何解决如何将多个ggplot图与同一构面下的不同数据框组合在一起?

所以,我有两个数据帧,它们产生了两个我想合并的具有相同构面的ggplots

第一个数据帧产生以下ggplot

Dataframe1

library(ggh4x)
library(ggnomics)
library(ggplot2)
library(data.table)

#dataframe
drug <- c("DrugA","DrugB1","DrugB2","DrugB3","DrugC1","DrugC2","DrugC3","DrugC4")
PR  <- c(18,430,156,60,66,113,250)
GR <- c(16,425,154,56,64,111,248)
PS  <- c(28,530,256,3,70,76,213,350)
GS <- c(26,525,254,5,74,211,348)
group<-c("n=88","n=1910","n=820","n=8","n=252","n=280","n=648","n=1186")
class<-c("Class A","Class B","Class C","Class C")
df <-data.frame(drug,group,class,PR,GR,PS,GS)

#make wide to long df
df.long <- melt(setDT(df),id.vars = c("drug","group","class"),variable.name = "type")

#Order of variables
df.long$type <- factor(df.long$type,levels=c("PR","GR","PS","GS"))
df.long$class <- factor(df.long$class,levels= c("Class B","Class A","Class C"))
df.long$group <- factor(df.long$group,levels= c("n=1910","n=88","n=1186"))
df.long$drug <- factor(df.long$drug,levels= c("DrugB1","DrugA","DrugC4"))

数据框1的ggplot


ggplot(df.long,aes(fill = type,x = drug,y = value)) + 
  geom_bar(aes(fill = type),stat = "identity",position = "dodge",colour="white") + 
  geom_text(aes(label = value),position = position_dodge(width = 1.2),vjust = -0.5)+ 
  scale_fill_manual(values = c("#fa9fb5","#dd1c77","#bcbddc","756bb1")) + 
  scale_y_continuous(expand = c(0,0),limits = c(0,600)) +
  theme(title = element_text(size = 18),legend.text = element_text(size = 12),axis.text.x = element_text(size = 9),axis.text.y =element_text(size = 15),plot.title = element_text(hjust = 0.5)) +
  ggh4x::facet_nested(.~class + group,scales = "free_x",space= "free_x")

这是第二个数据帧

#dataframe 2
drug <- c("DrugA","DrugC4")
Sens  <- c(0.99,0.97,NA,0.88,0.92,0.98,0.99)
Spec <- c(1,0.99,1,1)
class<-c("Class A","Class C")
df2 <-data.frame(drug,Sens,Spec)

#wide to long df2
df2.long <- melt(setDT(df2),variable.name = "type")

#additional variables
df2.long$UpperCI <- c(0.99,1)
df2.long$LowerCI  <- c(0.97,0.61,0.83,0.93,0.99)

#order of variables
df2.long$class <- factor(df2.long$class,"Class C"))

数据框2的ggplot

ggplot(df2.long,aes(x=drug,y=value,group=type,color=type)) + 
  geom_line() +
  geom_point()+
  geom_errorbar(aes(ymin=LowerCI,ymax=UpperCI),width=.2,position=position_dodge(0.05)) +
  scale_y_continuous(labels=scales::percent)+
  labs(x="drug",y = "Percentage")+
  theme_classic() +
  scale_color_manual(values=c('#999999','#E69F00')) + 
  theme(legend.text=element_text(size=12),axis.text.x=element_text(size=9),axis.text.y =element_text(size=15),panel.background = element_rect(fill = "whitesmoke"))+
  facet_wrap(facets = vars(class),scales = "free_x")

因此,我试图在一个方面(数据帧1中的一个)下合并两个图,到目前为止,我已经完成了以下操作

ggplot(df.long)+
  aes(x=drug,fill = type)+
  geom_bar(,colour="white") + 
  geom_text(aes(label=value),position=position_dodge(width=0.9),vjust=-0.5,size=2) + 
  scale_fill_manual(breaks=c("PR","GS"),values=c("#dd1c77","#756bb1","#fa9fb5","#e7e1ef","black","black")) + 
  scale_y_continuous(expand = c(0,1100),sec.axis=sec_axis(~./10,labels = function(b) { paste0(b,"%")},name="Percentage")) + #remove space between x axis labels and bottom of chart
  theme(legend.text=element_text(size=12),legend.position = 'bottom',panel.background = element_rect(fill = "whitesmoke"),#color of plot background
        panel.border = element_blank(),#remove border panels of each facet
        strip.background = element_rect(colour = NA)) +  #remove border of strip
  labs(y = "Number of isolates",fill = "")+
  geom_errorbar(data=df2.long,y=value*1000,ymin=LowerCI*1000,ymax=UpperCI*1000,color=type),position=position_dodge(0.05))+
  geom_point(data=df2.long,show.legend = F)+
  geom_line(data=df2.long,color=type)) +
  scale_color_manual(values=c('#999999','#E69F00'))

但是我坚持从plot1添加构面。我希望任何人都可以帮助:)

解决方法

对于这种特定情况,我认为嵌套面不是合适的解决方案,因为n = ...似乎是x轴组的元数据,而不是类的子类别。

以下是您可以使用facet_grid()绘制数据的方法:

ggplot(df.long,aes(drug,value,fill = type)) +
  geom_col(position = "dodge") +
  geom_text(aes(label = value),position = position_dodge(0.9),vjust = -0.5,size = 2) +
  geom_errorbar(data = df2.long,aes(y = value * 1000,color = type,ymin = LowerCI * 1000,ymax = UpperCI * 1000),position = position_dodge(0.05),width = 0.2) +
  geom_point(data = df2.long,color = type),show.legend = FALSE) +
  geom_line(data = df2.long,group = type,color = type)) +
  scale_fill_manual(breaks = c("PR","GR","PS","GS"),values=c("#dd1c77","#756bb1","#fa9fb5","#e7e1ef","black","black")) +
  scale_color_manual(values=c('#999999','#E69F00')) +
  scale_y_continuous(expand = c(0,0),limits = c(0,1100),sec.axis = sec_axis(~ ./10,labels = function(b) {
                                           paste0(b,"%")
                                         },name = "Percentage")) +
  scale_x_discrete(
    labels = levels(interaction(df.long$drug,df.long$group,sep = "\n"))
  ) +
  facet_grid(~ class,scales = "free_x",space = "free_x") +
  theme(legend.text=element_text(size=12),legend.position = 'bottom',axis.text.x=element_text(size=9),axis.text.y =element_text(size=15),panel.background = element_rect(fill = "whitesmoke"),#color of plot background
        panel.border = element_blank(),#remove border panels of each facet
        strip.background = element_rect(colour = NA)) 

enter image description here

如果您坚持使用n = ...标签,也许更好的方法是将它们添加为文本,即添加以下内容:

  stat_summary(fun = sum,aes(group = drug,y = stage(value,after_stat = -50),label = after_stat(paste0("n = ",y))),geom = "text") +

例如,将y轴限制设置为c(-100,1000)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-