本文介绍了gplot2覆盖barplot和线图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我复制了一行代码,用于从本网站上的某位代码处获取代码,以便如何使用两个y轴叠加两个图。但是,该示例使用了两条线图,但我想要叠加一条线图和一条条形图。我似乎无法获得覆盖层,它只是绘制线条图。请帮忙。 库(ggplot2)库(gtable)库(网格) require(ggplot2) df1 df2< -data.frame( type = factor(c(吉祥物,mstat),levels = c(吉祥物,mstat)),frax = c(30,35,40,45,50,55),phos = c(542,413,233,500,600,650)) p1 p2 #覆盖第一个绘图的第二个绘图面板pp< -c(子集(g1 $ layout,name ==)面板,se = t:r)) g< -gtable_add_grob(g1, g2 $ grobs [[which(g2 $ layout $ name ==panel)]], pp $ t,pp $ l,pp $ b,pp $ l) #axis tweaks alab< -g2 $ grobs [[which(g2 $ layout $ name ==ylab )]] ia< -which(g2 $ layout $ name ==axis-l) ga< -g2 $ grobs [[ia]] ax< -ga $ children [[2]] ax $ widths< -rev(ax $ widths) ax $ grobs< -rev(ax $ grobs) ax $ grobs [[1]] $ x< ; -ax $ grobs [[1]] $ x-unit(1,npc)+ 单位(0.15,cm) g length(g $ widths)-1) g 长度(g $宽度)-1) g g grid.draw(g) 我希望输出看起来完全(或非常相似):但是,我想让barplot躲闪 解决方案这大部分都是你想要的:向内指向刻度标记,来自两个图的组合图例,两个图的重叠,以及将一个图的y轴移动到 library(ggplot2)#version 2.2.1 library(gtable)#version 0.2 .0 library(grid) #您的数据 df1 df2 frax = c(30,35,40,45,50,55),phos = c(542,413,233,500,600,650)) #基底图 p1 geom_bar(stat =identity,position =dodge)+ scale_x_continuous(fractions,expand = c(0,0) ,limit = c(16,64), breaks = seq(20,60,5),labels = seq(20,60,5))+ scale_y_continuous(Phospho hits,breaks = seq(0,1400,250),expand = c(0,0),限制= c(0,700))+ scale_fill_discrete()+ theme_bw()+ theme(panel.grid = element_blank(), legend.key =面板内的元素正确(color =white), axis.ticks.length =单位(-1,mm),#tick标记 axis.text.x = element_text(margin = margin (t = 7,b = 0)),#调整文本边距 axis.text.y = element_text(margin = margin(l = 0,r = 7))) p2 geom_line(aes(linetype =LC Gradient),color =blue,size = .75)+ scale_x_continuous(fractions,expand = c(0,0),limits = c(16,64))+ scale_y_continuous(%Solvent B)+ scale_linetype_manual(,values =longdash)+ theme_bw()+ theme(panel.background = element_rect(fill =transparent), panel.grid = element_blank(), axis .ticks.length =单位(-1,mm), axis.text.x = element_text(margin = mar gin(t = 7,b = 0)), axis.text.y = element_text(margin = margin(l = 0,r = 7)), legend.key.width = unit 1.5,cm),#加宽键 legend.key = element_rect(color =white)) #提取gtables g1< - ggplotGrob(p1) g2< - ggplotGrob(p2) #获取他们的传说 leg1 = g1 $ grobs [[which(g1 $ layout $ name ==导航盒)]] leg2 = g2 $ grobs [[其中(g2 $ layout $ name ==guide-box)]] #将它们加入一个图例 leg = cbind(leg1,leg2,size =first)#稍后定位的腿 #从两个gtable中删除图例 pos = subset(g1 $ layout ,grepl(guide-box,name),l) g1 = g1 [,-pos $ l] g2 = g2 [,-pos $ l] ##取自http://stackoverflow.com/questions/36754891/ggplot2-adding-secondary-y-axis-on-top-of-a-plot/36759348#36759348 #的代码将y轴移动到右侧 #获取g1中绘图面板的位置。 #这些在稍后将g2的转换元素放回到g1 pp $ b#第一个图的第二个图的重叠面板 g1 #ggplot包含很多标签本身就是复杂的grob; #通常是由边距包围的文字。 #当从图的左边到右边移动grobs时,#确保边距和理由被交换。 #下面的函数进行交换。 #取自cowplot包:#https://github.com/wilkelab/cowplot/blob/master/R/switch_axis.R hinvert_title_grob< - 函数(grob){ #交换宽度宽度< - grob $ widths grob $ widths [1]< - widths [3] grob $ widths [1] grob $ vp [[1]] $ layout $ widths [1]< - widths [3] grob $ vp [[1]] $ layout $ widths [3]< - widths [1] #修复理由 grob $ children [[1]] $ hjust< - 1 - grob $ children [[1 ]] $ hjust grob $ children [[1]] $ vjust< - 1 - grob $ children [[1]] $ vjust grob $ children [[1]] $ x grob } #从g2 索引获取y轴标题< - 其中(g2 $ layout $ name ==ylab-l)#哪个grob包含y轴标题? ylab ylab # g1 g1 g1 # g2(轴线,刻度线和刻度线标记) index< - 其中(g2 $ layout $ name ==axis-l)#其中grob yaxis< - g2 $ grobs [[index]]#提取grob #yaxis是一个包含轴线,刻度线和刻度标记标记的组合。 #相关的grobs包含在axis $ children中:#axis $ children [[1]]包含轴线; #轴$ children [[2]]包含刻度线和刻度线标签。 #首先,将轴线移动到左边 yaxis $ children [[1]] $ x #其次,交换刻度标记和刻度标记刻度< - yaxis $ children [[2]] 刻度$宽度< - rev(ticks $ widths) ticks $ grobs< - rev(ticks $ grobs) #第三,移动勾号 ticks $ grobs [[1]] $ x #第四,调整保证金和固定理由对于刻度标记 ticks $ grobs [[2]]< - hinvert_title_grob(ticks $ grobs [[2]]) #五,将滴答放回yaxis yaxis $ children [[2]] #将变换后的y轴放在g1 g1 g1 #绘制 grid.newpage() grid.draw(g1) #在视口中添加图例vp = viewport(x = 0.3,y = 0.92,height = .2,width = .2) pushViewport(vp) grid.draw(leg) upViewport() g = grid.grab() grid.newpage() grid.draw(g) I copied line for line a code from someone on this site on how to overlay two plots with two y axes. However, the example uses two line plots, but I have one line plot and one barplot that I want to overlay. I can't seem to obtain an overlay at all and it just plots the line plot. Please help. Thanks. library(ggplot2)library(gtable)library(grid)require(ggplot2)df1 <- data.frame(frax=c(0,30,60,114),solvb=c(0,0,100,100))df2 <-data.frame( type = factor(c("mascot","mstat"), levels=c("mascot","mstat")), frax = c(30,35,40,45,50,55), phos=c(542,413,233,500,600,650))p1<-ggplot(df2,aes(x=frax, y=phos,fill=type)) + geom_bar(stat="identity",position="dodge") + scale_x_continuous("fractions",breaks=seq(1,115,2)) + scale_y_continuous("Phospho hits",breaks=seq(0,1400,250))p2<-ggplot(df1,aes(x=frax,y=solvb)) + geom_line(colour="blue")#extract gtableg1<-ggplot_gtable(ggplot_build(p1))g2<-ggplot_gtable(ggplot_build(p2))#overlap the panel of 2nd plot on that of 1st plotpp <-c(subset(g1$layout, name == "panel", se=t:r))g<-gtable_add_grob(g1, g2$grobs[[which(g2$layout$name == "panel")]], pp$t,pp$l,pp$b,pp$l)#axis tweaksalab<-g2$grobs[[which(g2$layout$name=="ylab")]]ia<-which(g2$layout$name == "axis-l")ga<-g2$grobs[[ia]]ax<-ga$children[[2]]ax$widths<-rev(ax$widths)ax$grobs<-rev(ax$grobs)ax$grobs[[1]]$x<-ax$grobs[[1]]$x-unit(1,"npc")+ unit(0.15,"cm")g<-gtable_add_cols(g,g2$widths[g2$layout[ia,]$l], length(g$widths)-1)g<-gtable_add_cols(g, g2$widths[g2$layout[ia,]$l], length(g$widths)-1)g<-gtable_add_grob(g,ax,pp$t,length(g$widths) - 2,pp$b)g<-gtable_add_grob(g,alab,pp$t,length(g$widths) - 1,pp$b)grid.draw(g)I would like for the output to look exactly (or very similar) to this: However, I want the barplot "dodged" 解决方案 This does most of what you want: inward pointing tick marks, combined legends from two plots, overlapping of two plots, and moving the y-axis of one to the right side of the plot.library(ggplot2) # version 2.2.1library(gtable) # version 0.2.0library(grid)# Your datadf1 <- data.frame(frax = c(16,30,60,64), solvb = c(0,0,100,100))df2 <- data.frame(type = factor(c("mascot","mstat"), levels = c("mascot","mstat")), frax = c(30,35,40,45,50,55), phos = c(542,413,233,500,600,650))# Base plotsp1 <- ggplot(df2, aes(x = frax, y = phos, fill = type)) + geom_bar(stat = "identity", position = "dodge") + scale_x_continuous("fractions", expand = c(0,0), limits = c(16, 64), breaks = seq(20,60,5), labels = seq(20, 60, 5)) + scale_y_continuous("Phospho hits", breaks = seq(0,1400,250), expand = c(0,0), limits = c(0, 700)) + scale_fill_discrete("") + theme_bw() + theme(panel.grid = element_blank(), legend.key = element_rect(colour = "white"), axis.ticks.length = unit(-1, "mm"), #tick marks inside the panel axis.text.x = element_text(margin = margin(t = 7, b = 0)), # Adjust the text margins axis.text.y = element_text(margin = margin(l = 0, r = 7)))p2 <- ggplot(df1, aes(x = frax, y = solvb)) + geom_line(aes(linetype = "LC Gradient"), colour = "blue", size = .75) + scale_x_continuous("fractions", expand = c(0,0), limits = c(16, 64)) + scale_y_continuous("% Solvent B") + scale_linetype_manual("", values="longdash") + theme_bw() + theme(panel.background = element_rect(fill = "transparent"), panel.grid = element_blank(), axis.ticks.length = unit(-1, "mm"), axis.text.x = element_text(margin = margin(t = 7, b = 0)), axis.text.y = element_text(margin = margin(l = 0, r = 7)), legend.key.width = unit(1.5, "cm"), # Widen the key legend.key = element_rect(colour = "white"))# Extract gtablesg1 <- ggplotGrob(p1)g2 <- ggplotGrob(p2)# Get their legendsleg1 = g1$grobs[[which(g1$layout$name == "guide-box")]]leg2 = g2$grobs[[which(g2$layout$name == "guide-box")]]# Join them into one legendleg = cbind(leg1, leg2, size = "first") # leg to be positioned later# Drop the legends from the two gtablespos = subset(g1$layout, grepl("guide-box", name), l)g1 = g1[, -pos$l]g2 = g2[, -pos$l]## Code taken from http://stackoverflow.com/questions/36754891/ggplot2-adding-secondary-y-axis-on-top-of-a-plot/36759348#36759348# to move y axis to right hand side# Get the location of the plot panel in g1.# These are used later when transformed elements of g2 are put back into g1pp <- c(subset(g1$layout, name == "panel", se = t:r))# Overlap panel for second plot on that of the first plotg1 <- gtable_add_grob(g1, g2$grobs[[which(g2$layout$name == "panel")]], pp$t, pp$l, pp$b, pp$l)# ggplot contains many labels that are themselves complex grob; # usually a text grob surrounded by margins.# When moving the grobs from, say, the left to the right of a plot,# Make sure the margins and the justifications are swapped around.# The function below does the swapping.# Taken from the cowplot package:# https://github.com/wilkelab/cowplot/blob/master/R/switch_axis.R hinvert_title_grob <- function(grob){ # Swap the widths widths <- grob$widths grob$widths[1] <- widths[3] grob$widths[3] <- widths[1] grob$vp[[1]]$layout$widths[1] <- widths[3] grob$vp[[1]]$layout$widths[3] <- widths[1] # Fix the justification grob$children[[1]]$hjust <- 1 - grob$children[[1]]$hjust grob$children[[1]]$vjust <- 1 - grob$children[[1]]$vjust grob$children[[1]]$x <- unit(1, "npc") - grob$children[[1]]$x grob}# Get the y axis title from g2index <- which(g2$layout$name == "ylab-l") # Which grob contains the y axis title?ylab <- g2$grobs[[index]] # Extract that grobylab <- hinvert_title_grob(ylab) # Swap margins and fix justifications# Put the transformed label on the right side of g1g1 <- gtable_add_cols(g1, g2$widths[g2$layout[index, ]$l], pp$r)g1 <- gtable_add_grob(g1, ylab, pp$t, pp$r + 1, pp$b, pp$r + 1, clip = "off", name = "ylab-r")# Get the y axis from g2 (axis line, tick marks, and tick mark labels)index <- which(g2$layout$name == "axis-l") # Which grobyaxis <- g2$grobs[[index]] # Extract the grob# yaxis is a complex of grobs containing the axis line, the tick marks, and the tick mark labels.# The relevant grobs are contained in axis$children:# axis$children[[1]] contains the axis line;# axis$children[[2]] contains the tick marks and tick mark labels.# First, move the axis line to the leftyaxis$children[[1]]$x <- unit.c(unit(0, "npc"), unit(0, "npc"))# Second, swap tick marks and tick mark labelsticks <- yaxis$children[[2]]ticks$widths <- rev(ticks$widths)ticks$grobs <- rev(ticks$grobs)# Third, move the tick marksticks$grobs[[1]]$x <- ticks$grobs[[1]]$x - unit(1, "npc") + unit(-1, "mm")# Fourth, swap margins and fix justifications for the tick mark labelsticks$grobs[[2]] <- hinvert_title_grob(ticks$grobs[[2]])# Fifth, put ticks back into yaxisyaxis$children[[2]] <- ticks# Put the transformed yaxis on the right side of g1g1 <- gtable_add_cols(g1, g2$widths[g2$layout[index, ]$l], pp$r)g1 <- gtable_add_grob(g1, yaxis, pp$t, pp$r + 1, pp$b, pp$r + 1, clip = "off", name = "axis-r")# Draw itgrid.newpage()grid.draw(g1)# Add the legend in a viewportvp = viewport(x = 0.3, y = 0.92, height = .2, width = .2)pushViewport(vp)grid.draw(leg)upViewport()g = grid.grab()grid.newpage()grid.draw(g) 这篇关于gplot2覆盖barplot和线图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-25 15:37