2011-03-07 66 views
12

我知道當你使用par(fig=c(...), new=T)時,你可以創建插圖。但是,我想知道是否可以使用ggplot2庫來創建'插圖'圖。可以創建插圖?

更新1:我嘗試使用par()與ggplot2,但它不起作用。

更新2:我使用grid::viewport()ggplot2 GoogleGroups找到了一個工作解決方案。

回答

21

the book的8.4部分解釋瞭如何做到這一點。訣竅是使用grid包的viewport s。

#Any old plot 
a_plot <- ggplot(cars, aes(speed, dist)) + geom_line() 

#A viewport taking up a fraction of the plot area 
vp <- viewport(width = 0.4, height = 0.4, x = 0.8, y = 0.2) 

#Just draw the plot twice 
png("test.png") 
print(a_plot) 
print(a_plot, vp = vp) 
dev.off() 
+2

值得指出的是,如果一個人想另一個情節作爲插入,關鍵是'print(another_plot,vp = vp)',我花了一段時間才弄清楚。+1 – mts 2017-04-09 20:44:47

2

Learning R博客上的這post接着如何在劇情內進行繪圖。這個博客在ggplot2上有很多其他很棒的帖子。

+0

鏈接的文章和Richie使用'grid :: viewport()'的方法是一樣的。 – zx8754 2016-08-19 20:57:56

10

我更喜歡使用ggsave的解決方案。很多周圍的Googling後,我結束了與此(這是位置和尺寸,你插入的情節通式。

library(tidyverse) 

plot1 = qplot(1.00*mpg, 1.00*wt, data=mtcars) # Make sure x and y values are floating values in plot 1 
plot2 = qplot(hp, cyl, data=mtcars) 
plot(plot1) 

# Specify position of plot2 (in percentages of plot1) 
# This is in the top left and 25% width and 25% height 
xleft = 0.05 
xright = 0.30 
ybottom = 0.70 
ytop = 0.95 

# Calculate position in plot1 coordinates 
# Extract x and y values from plot1 
l1 = ggplot_build(plot1) 
x1 = l1$layout$panel_ranges[[1]]$x.range[1] 
x2 = l1$layout$panel_ranges[[1]]$x.range[2] 
y1 = l1$layout$panel_ranges[[1]]$y.range[1] 
y2 = l1$layout$panel_ranges[[1]]$y.range[2] 
xdif = x2-x1 
ydif = y2-y1 
xmin = x1 + (xleft*xdif) 
xmax = x1 + (xright*xdif) 
ymin = y1 + (ybottom*ydif) 
ymax = y1 + (ytop*ydif) 

# Get plot2 and make grob 
g2 = ggplotGrob(plot2) 
plot3 = plot1 + annotation_custom(grob = g2, xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax) 
plot(plot3) 

ggsave(filename = "test.png", plot = plot3) 

# Try and make a weird combination of plots 
g1 <- ggplotGrob(plot1) 
g2 <- ggplotGrob(plot2) 
g3 <- ggplotGrob(plot3) 

library(gridExtra) 
library(grid) 

t1 = arrangeGrob(g1,ncol=1, left = textGrob("A", y = 1, vjust=1, gp=gpar(fontsize=20))) 
t2 = arrangeGrob(g2,ncol=1, left = textGrob("B", y = 1, vjust=1, gp=gpar(fontsize=20))) 
t3 = arrangeGrob(g3,ncol=1, left = textGrob("C", y = 1, vjust=1, gp=gpar(fontsize=20))) 

final = arrangeGrob(t1,t2,t3, layout_matrix = cbind(c(1,2), c(3,3))) 
grid.arrange(final) 

ggsave(filename = "test2.png", plot = final) 

Image showing inset and relatively complex layout

+0

我認爲他們已經更新了ggplot包,現在爲了從plot1座標中提取位置,格式應該是這樣的:'l1 $ layout $ panel_ranges [[1]] $ x.range [1]'。請注意'l1 $ layout $ panel_ranges ....' – anotherFishGuy 2017-12-04 21:39:34

+0

你說得對。我已經相應地更新了答案。 – pallevillesen 2017-12-14 09:42:49

相關問題