我正在尝试使用R在同一个图上绘制几组有序对。我不需要它们之间的线,因为已经通过简单的线性回归来处理。这是一些示例代码:
sw_sd <- c(0, 20)
sw_r <- c(5, 10)
aa_sd <- c(0, 16)
aa_r <- c(5, 8)
png("5-airline-cals.png")
plot.new()
plot.window(xlim=c(0,25), ylim=c(0,12))
plot(c(aa_sd, aa_r))
plot(sw_sd,sw_r, pch=22, main="Capital Allocation Lines", xlab="Standard Deviation", ylab="Expected Return")
sw_cal=lm(sw_r~sw_sd)
aa_cal=lm(aa_r~aa_sd)
abline(sw_cal, col="forestgreen", lwd=3)
abline(aa_cal, col="blue", lwd=3)
legend(1, 9, c("Southwest Airlines","American Airlines"), cex=0.8, col=c("forestgreen","blue"), lwd=3);
box()
dev.off()
sd
对是x坐标,r
是y坐标。我需要在同一个散点图上设置两组x-y对。这是简化的数据,但你明白了。
答案 0 :(得分:6)
对于RTFM评论的推文感到抱歉。这里有更多细节。
使用基本图形,我会通过以下方式完成你正在做的事情:
plot(c(sw_sd,aa_sd),c(sw_r,aa_r), pch = 22,
col = rep(c('forestgreen','blue'),each = 2),main="Capital Allocation Lines",
xlab="Standard Deviation", ylab="Expected Return")
abline(lm(sw_r~sw_sd),col = 'forestgreen',lwd = 3)
abline(lm(aa_r~aa_sd),col = 'blue',lwd = 3)
我提到points
和lines
的原因是因为您询问如何在同一图表上绘制多组点。 R中使用基本图形的一般策略是,只需调用plot
即可初始化一个图,然后使用points
,lines
等内容添加 ,abline
等。
您对plot.new
和plot.window
的来电并非真的有必要;如果你只是从R开始,你可能暂时不需要使用它们,真的。
通常,每次拨打plot
时,R都会启动新的绘图设备。因此,您对plot
的重复呼叫只会重新开始并重新开始。您会注意到结果绘图最终没有y轴限制为0到12.这是因为每次重新调用plot
时,您都是从头开始,就像之前的命令从未发生过一样。这也是为什么没有出现其他一组点的原因。
最后,阅读?plot
的建议有点误导,因为真正的?plot.default
对于初学者来说更具信息性。它有很少的块,比如能够直接传递x和y轴限制,传递type = "n"
以创建一个具有正确尺寸的空图,然后可以添加,等等。
答案 1 :(得分:3)
基于ggplot
的快速回答:
dat <- data.frame(sd=c(0,20,0,16),
r=c(5,10,5,8),
airline=rep(c("Southwest","American"),each=2))
library(ggplot2)
theme_update(theme_bw())
qplot(sd,r,data=dat,colour=airline)+geom_smooth(method="lm")+
labs(x="Standard Deviation",y="Expected Return")+
scale_colour_manual(value=c("forestgreen","blue"))
答案 2 :(得分:2)
使用Ben但有格子的数据框:
library(lattice)
xyplot(r~sd, data=dat, groups=airline,
type=c('p', 'r'),
auto.key=list(space='right'),
main="Capital Allocation Lines",
xlab="Standard Deviation", ylab="Expected Return")
您可以在?panel.xyplot
和?xyplot
找到详细信息。