我一直在尝试使用ggplot2
和lattice
绘制数据面板。我在围绕ggplot2
模型进行整理时遇到了一些麻烦。特别是,如何在每个面板上绘制包含两组数据的散点图:
在lattice
中,我可以这样做:
xyplot(Predicted_value + Actual_value ~ x_value | State_CD, data=dd)
这将为我为每个State_CD的每一列提供一个面板
我可以用
ggplot2
做一栏:pg <- ggplot(dd, aes(x_value, Predicted_value)) + geom_point(shape = 2)
+ facet_wrap(~ State_CD) + opts(aspect.ratio = 1)
print(pg)
我无法理解的是如何将Actual_value添加到上述ggplot中。
编辑哈德利指出,使用可重现的示例确实会更容易。这似乎有效的代码。有没有更好或更简洁的方法可以通过ggplot做到这一点?为什么将另一组点添加到ggplot的语法与添加第一组数据有何不同?
library(lattice)
library(ggplot2)
#make some example data
dd<-data.frame(matrix(rnorm(108),36,3),c(rep("A",24),rep("B",24),rep("C",24)))
colnames(dd) <- c("Predicted_value", "Actual_value", "x_value", "State_CD")
#plot with lattice
xyplot(Predicted_value + Actual_value ~ x_value | State_CD, data=dd)
#plot with ggplot
pg <- ggplot(dd, aes(x_value, Predicted_value)) + geom_point(shape = 2) + facet_wrap(~ State_CD) + opts(aspect.ratio = 1)
print(pg)
pg + geom_point(data=dd,aes(x_value, Actual_value,group=State_CD), colour="green")
晶格输出如下所示:
(来源:cerebralmastication.com)
ggplot看起来像这样:
(来源:cerebralmastication.com)
最佳答案
只需遵循Ian的建议即可:对于ggplot2,您确实希望将所有y轴内容放在一列中,而另一列作为要显示其装饰方式的因素。使用melt
可以很容易地做到这一点。以机智:
qplot(x_value, value,
data = melt(dd, measure.vars=c("Predicted_value", "Actual_value")),
colour=variable) + facet_wrap(~State_CD)
这是我的样子:
(来源:princeton.edu)
为了了解
melt
的实际作用,请看下面的图:> head(melt(dd, measure.vars=c("Predicted_value", "Actual_value")))
x_value State_CD variable value
1 1.2898779 A Predicted_value 1.0913712
2 0.1077710 A Predicted_value -2.2337188
3 -0.9430190 A Predicted_value 1.1409515
4 0.3698614 A Predicted_value -1.8260033
5 -0.3949606 A Predicted_value -0.3102753
6 -0.1275037 A Predicted_value -1.2945864
您会看到,它将“ Predicted_value”和“ Actual_value”“融合”到一个名为
value
的列中,并添加了另一个名为variable
的列,让您知道它最初来自哪一列。
关于r - 使用R在GGPLOT2散点图上绘制两个数据向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1313954/