2012-04-14 105 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