2011-03-13 47 views
56

傳說阿爾法我有風速對方向的圖具有點的巨大numeber,因此使用的α=我除了顏色我(1/20)=月如何設置GGPLOT2

這裏是的代碼的示例:

library(RMySQL) 
library(ggplot2) 
con <- dbConnect(...) 
wind <- dbGetQuery(con, "SELECT speed_w/speed_e AS ratio, dir_58 as dir, MONTHNAME(timestamp) AS month, ROUND((speed_w+speed_e)/2) AS speed FROM tablename;"); 

png("ratio-by-speed.png",height=400,width=1200) 
qplot(wind$dir,wind$ratio,ylim=c(0.5,1.5),xlim=c(0,360),color=wind$month,alpha=I(1/30),main="West/East against direction") 
dev.off() 

這產生一個體面圖表,但是我的問題是,圖例的α爲1/30日也,這使得它不可讀。有沒有一種方法可以強制圖例變成1 alpha?

下面是一個例子: Example Graph

+0

華麗的情節,BTW。 – 2015-07-28 21:10:09

回答

73

更新隨着0.9.0版本的發佈,一個現在可以在guides功能使用override.aes傳說改寫的審美價值。所以,如果你添加這樣的東西到你的情節:

+ guides(colour = guide_legend(override.aes = list(alpha = 1))) 

應該這樣做。


我已經通過使用數據的空子集做給GEOM重複呼叫,並使用來自呼叫傳說解決此得到。不幸的是,如果數據幀實際上是空的(如從subset(diamonds,FALSE)得到),它不起作用,因爲ggplot2似乎將這種情況視爲與將NULL視爲代替數據幀的情況相同。但是,我們可以通過僅使用一行的子集並將其設置爲NaN在一個繪圖維上獲得相同的效果,這將防止它被繪製。

基於關閉大通的例子:

# Alpha parameter washes out legend: 
gp <- ggplot() + geom_point(data=diamonds, aes(depth, price, colour=clarity), alpha=0.1) 
print(gp) 

# Full color legend: 
dummyData <- diamonds[1, ] 
dummyData$price <- NaN 
#dummyData <- subset(diamonds, FALSE) # this would be nicer but it doesn't work! 
gp <- ggplot() + 
    geom_point(data=diamonds, aes(depth, price, colour=clarity), alpha=0.1, legend=FALSE) + 
    geom_point(data=dummyData, aes(depth, price, colour=clarity), alpha=1.0, na.rm=TRUE) 
print(gp) 
+0

輝煌。這個解決方案很棒。只是試着去嘗試一下。爲@ joran的更新工作 – Chris 2011-03-30 22:17:52

+2

+1(以及現在不需要的很好的黑客) – Gregor 2012-04-30 17:48:37

+0

我使用的是0.9.3.1版本,但它對我無效。我已經把'guides()'函數放在了不同的位置,但是我沒有得到預期的行爲。任何提示? – polarise 2014-02-13 15:43:46

5

的谷歌搜索止跌回升this post這似乎並不表明ggplot有點目前支持此選項。其他人通過使用gridExtra並使用here討論的視口來解決相關問題。

我不是那麼複雜,但是這裏有一種方法可以給你想要的結果。方法是繪製幾何圖形,一次沒有alpha參數,並且在真實繪圖區域之外。第二個幾何將包含alpha參數並抑制圖例。然後我們將用xlim和ylim指定繪圖區域。考慮到你有很多的觀點,這將大約是時間的兩倍,但是應該給你後面的效果。

使用鑽石數據集:

#Alpha parameter washes out legend 
ggplot(data = diamonds, aes(depth, price, colour = clarity)) + 
geom_point(alpha = 1/10) 

#Fully colored legend 
ggplot() + 
geom_point(data = diamonds, aes(depth, price, colour =clarity), alpha = 1/10, legend = FALSE) + 
geom_point(data = diamonds, aes(x = depth - 999999, y = price - 999999, colour = clarity)) + 
xlim(40, 80) + ylim(0, 20000)