2016-11-10 43 views
0

我想绘制一个数据帧,其中X轴是从说df1和y轴必须被视为从另一个数据帧df2观察。下面给出了示例数据帧。如何绘制使用多个数据帧与Y轴是从另一个数据帧观测

df1 
id a b c 
id1 1.5 1.3 2.1 
id2 2.4 1.8 1.6 
id3 1.5 1.9 2.3 
... 
... 

df2 
list type parm 
1  a  xm 
2  b  gh 
3  c  tr 

从上面的示例数据框中我绘制了df1(ID在X轴上)和变量a,b,c的单独绘图,如下所示。

p1 <- ggplot(df1, aes(x = id, y = a)) + geom_boxplot(outlier.shape = NA) 
p1 
p2 <- ggplot(df1, aes(x = id, y = b)) + geom_boxplot(outlier.shape = NA) 
p2 
p3 <- ggplot(df1, aes(x = id, y = c)) + geom_boxplot(outlier.shape = NA) 
p3 
grid.arrange(p1,p2,p3,ncol = 1) 

我的问题是,有一个方法,得到y轴上从DF2输入,因为在DF1的变量a,b,c是在类型列在观测DF2。

我累了给下面

p1 <- ggplot(df1, aes(x = id, y = df2$type[1])) + geom_boxplot(outlier.shape = NA) 
p1 

但值不绘制。 此外,当我运行我的主代码时,这3个变量可以变成5个变量,甚至更像a,b,c,d,e,f,我希望我的绘图代码自动从df2中选择y轴,并使用df1中的对应值。 有没有简单的方法来绘制它。

+0

DF2 $型[1]将返回一个字符向量。所以你将不得不使用aes_string()。这是我对这个问题的第一个看法。 –

回答

0
df1 = data.frame(id = c("id1", "id2", "id3"), a= 1:3, b = 3:5, c = 4:6) 
df2 = data.frame(type = letters[1:3], parm = letters[11:13]) 
df2$type <- as.character(df2$type) 

library(ggplot2) 
p1 <- ggplot(df1, aes_string(x = "id", y = df2$type[1])) + geom_boxplot(outlier.shape = NA) 
p1 

output from above code

+0

我也使用'aes_string',但值不是密谋 – mockash

+0

@ash你可以检查类(df2 $类型)是factpr /字符?因为我猜它肯定是个角色。 –

+0

是的,它是一个字符 – mockash