ggplot2:使用带有零件数据的选定构面创建图 [英] ggplot2: create a plot using selected facets with part data

查看:111
本文介绍了ggplot2:使用带有零件数据的选定构面创建图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用

  1. 使用部分数据创建具有两个列的facet_grid的基础图.
  2. 使用数据的其余部分并在现有构面的顶部进行绘制,但仅使用单个列.
  1. Using part of the data to create a base plot with facet_grid of two columns.
  2. Use remaining part of the data and plot on top of the existing facets but using only a single column.

示例代码:

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)

输出图:

如何在g2图上包括g3图?生成的图应在两个小平面上两次包含g3两条线.

How to include g3 plot on g2 plot? The resulting plot should include the g3 two lines twice on two facets.

推荐答案

我假设下面的图就是您想要的.

I assume the plot below is what you were looking for.

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具有三个唯一值:ABC,因此,面Class~Type不能提供所需的绘图,因为您希望df2$Class == "A"的数据显示在各个面中.

For tasks like this I found it better to work with two datasets. Since the variable df2$class has three unique values: A, B and C, faceting Class~Type does not give you desired plot, since you want the data for df2$Class == "A" to be displayed in the respective facets.

这就是为什么我将df_1中的变量Class重命名为Class_1的原因,因为此变量仅包含两个唯一值:BC. 刻面Class_1 ~ Type可让您在顶部绘制df2$Class == "A"的数据,而不会被Class刻面.

That's why I renamed variable Class in df_1 to Class_1 because this variable only contains two unique values: B and C. Faceting Class_1 ~ Type allows you to plot the data for df2$Class == "A" on top without being faceted by Class.

修改

根据下面的评论,这里是仅使用一个数据集的解决方案

Based on the comment below here is a solution using only one dataset

g2 + geom_line(data = filter(df2, Class == 'A')[, -1], 
               aes(X, Y, linetype = Type, col = "A"))


相似/相同的问题: 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆