2012-04-14 101 views
1

我正在寻找旋转X轴的散点图。基本上,我想绘制2个Y轴之间的相关性。理想情况下,我想有x轴表示时间和Y轴表示相关2个Y轴之间的图相关

data <- data.frame(words = c("Aliens", "Aliens", "Constitution", "Constitution", "Entitled", "Entitled"), 
       dates = as.Date(c ("2010-01-05", "2010-02-13", "2010-04-20", "2010-06-11","2010-03-18", "2010-09-13")), 
        Rep = c(.18, .14, .16, .45, .33, .71), Dem = c(.16, .38, .24, .11, .59, .34)) 

而这就是我能到目前为止做的。我不认为它真的得到了重点。我可以通过月份的相关性和颜色来确定尺寸?

plot(x=data$dates, y=data$Rep, ylim=c(0,1.1*max(data$Rep)), 
col='blue', pch = 15, 
main='Rep Correlations stock close', xlab='date', ylab='Republican') 
axis(2, pretty(c(0, 1.1*max(data$Rep))), col='blue') 
par(new=T) 
plot(x=data$date, y=data$Dem, ylim=c(0,1.1*max(data$Dem)), 
col='green', pch = 20, 
xaxt='n', axes = F, xlab = '', ylab='') 
axis(4, pretty(c(0, 1.1*max(data$Dem))), col='green') 
mtext("Democrat",side=4) 

任何想法/提示吗?

+0

如果你想看看Rep'和'Dem'之间'的相关性,然后哟你应该使用双变量图而不是2 y坐标轴。您可以使用颜色来编码时间,就像您所建议的那样,但另一个不错的方法是使用运动图表。就像你还提到的那样,这可以让你甚至使用点大小编码第三个变量。这是一个“运动气泡图”。以下是一个很好地显示效果的示例:http://code.google.com/p/google-motion-charts-with-r/ – 2012-04-14 22:32:15

+0

谢谢!我玩弄了运动图表,但从我能找到的/代码中,googlviz版本只允许时间在几天或几年。换句话说,我无法获得按月排列的日期。我对双变量情节也不太熟悉。这是你的意思吗? [图库](http://addictedtor.free.fr/graphiques/graphcode.php?graph=104) – crock1255 2012-04-15 19:51:29

回答

2

跟进上述@ JohnColby的评论(看How can I plot with 2 different y-axes?http://rwiki.sciviews.org/doku.php?id=tips:graphics-base:2yaxes为论据,为什么你应该创建双y轴图,如果你能帮助它),怎么样:

dat <- data ## best not to use reserved words -- it can cause confusion 
library(ggplot2) 
theme_update(theme_bw()) ## I prefer this theme 
## code months as a factor 
dat$month <- factor(months(dat$dates),levels=month.name) 
dat <- dat[order(dat$dates),] 
qplot(Rep,Dem,colour=month,data=dat)+ 
    geom_path(aes(group=1),colour="gray")+geom_point(alpha=0.4)+ 
    geom_text(aes(label=words),size=4) 

(添加点之间的线,然后重新绘制点,所以他们不会被遮挡线;加入的话是可爱的,但可能是完整的数据集太杂乱)

enter image description here

或者编码日期作为一个连续变量

ggplot(dat,aes(Rep,Dem,colour=dates))+ 
    geom_path(aes(group=1),colour="gray")+geom_point(alpha=0.4)+ 
    geom_text(aes(label=words),size=4)+ 
    expand_limits(x=c(0,0.9)) 
ggsave("plotcorr2.png",width=6,height=3) 

enter image description here

在这种特定情况下(其中两个变量都以相同的规模衡量),有也没有错,绘制他们都是违反日期轴:

library(reshape2) 
library(plyr) 
m1 <- rename(melt(dat,id.vars=c("words","dates","month")), 
      c(variable="party")) 

ggplot(m1,aes(dates,value,colour=party))+geom_line()+ 
    geom_text(aes(label=words),size=3)+ 
    expand_limits(x=as.Date(c("2009-12-15","2010-10-01"))) 
ggsave("plotcorr3.png",width=6,height=3) 

enter image description here

+0

我喜欢这个。我对双轴问题的理解是,如果它们的规模不同。我的想法是,在这种情况下,它会保持不变,因为它们的尺寸相同,但我喜欢它。 谢谢! – crock1255 2012-04-15 19:57:44

+0

你是对的。我没在想。在这种情况下,以相同的比例绘制这两个变量都很好。 'matplot'可以在基本的R图形中完成,重塑是'ggplot'的首选方法。 – 2012-04-15 20:50:09