1

我正在寻找带有旋转 X 轴的散点图。基本上,我想绘制 2 个 Y 轴之间的相关性。理想情况下,我希望 x 轴代表时间,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)

有什么想法/提示吗?

4

1 回答 1

2

跟进@JohnColby 上面的评论(请参阅我如何使用 2 个不同的 y 轴进行绘图?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)

(在点之间添加线,然后重新绘制点,这样它们就不会被线遮住;添加单词很可爱,但对于整个数据集来说可能太混乱了)

在此处输入图像描述

或将日期编码为连续变量

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)

在此处输入图像描述

在这个特定的上下文中(两个变量都在相同的尺度上测量),将它们都绘制在日期轴上也没有错:

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)

在此处输入图像描述

于 2012-04-15T15:38:27.797 回答