我想用
创建一个情节facet_grid
的基础图。示例代码:
library(ggplot2)
library(gridExtra)
df2 <- data.frame(Class=rep(c('A','B','C'),each=20),
Type=rep(rep(c('T1','T2'),each=10), 3),
X=rep(rep(1:10,each=2), 3),
Y=c(rep(seq(3,-3, length.out = 10),2),
rep(seq(1,-4, length.out = 10),2),
rep(seq(-2,-8, length.out = 10),2)))
g2 <- ggplot() + geom_line(data = df2 %>% filter(Class %in% c('B','C')),
aes(X,Y,color=Class, linetype=Type)) +
facet_grid(Type~Class)
g3 <- ggplot() + geom_line(data = df2 %>% filter(Class == 'A'),
aes(X,Y,color=Class, linetype=Type)) +
facet_wrap(~Type)
grid.arrange(g2, g3)
输出图:
如何在g3
情节中加入g2
情节?结果图应在两个方面包括g3
两行两次。
答案 0 :(得分:1)
我认为下面的情节是你要找的。
library(dplyr)
library(ggplot2)
df_1 <- filter(df2, Class %in% c('B','C')) %>%
dplyr::rename(Class_1 = Class)
df_2 <- filter(df2, Class == 'A')
g2 <- ggplot() +
geom_line(data = df_1,
aes(X, Y, color = Class_1, linetype = Type)) +
geom_line(data = df_2,
aes(X, Y, color = Class, linetype = Type)) +
facet_grid(Type ~ Class_1)
g2
<强>的解释强>
对于这样的任务,我发现使用两个数据集会更好。由于变量df2$class
有三个唯一值:A
,B
和C
,因此您需要数据,因此Class~Type
不会为您提供所需的图表df2$Class == "A"
显示在各个方面。
这就是我将Class
中的变量df_1
重命名为Class_1
的原因,因为此变量只包含两个唯一值:B
和C
。
通过构面Class_1 ~ Type
,您可以在df2$Class == "A"
上方绘制Class
的数据,而不会被g2 + geom_line(data = filter(df2, Class == 'A')[, -1],
aes(X, Y, linetype = Type, col = "A"))
分割。
修改强>
根据下面的评论,此处是仅使用一个数据集的解决方案
{{1}}
相似/同一问题:ggplot2:: Facetting plot with the same reference plot in all panels