2017-02-14 58 views
1

我試圖製作一個包含矩形的圖。我使用ggplot2創建它們,並希望通過將它們轉換爲繪圖對象來「使它們交互」。 現在的問題是,轉換到plotly似乎鬆動ggplot2中指定的矩形顏色。將ggplot2彩色矩形轉換爲灰色

這裏是一個小的自我解釋的代碼示例:

test.dat <- data.frame(xmin=c(0,1.5), ymin=c(-1,-1), xmax=c(1,2), ymax=c(1,1), col=c("blue", "red")) 
ggp.test <- ggplot() + geom_rect(data=test.dat, aes(xmin=xmin, ymin=ymin, xmax=xmax, ymax=ymax), fill=test.dat$col) + theme_bw() 
ggp.test 

ply.test <- plotly_build(ggp.test) 
ply.test 

有趣的是,當我像下面指定懸停信息,然後顏色是正確的:

test.dat <- data.frame(xmin=c(0,1.5), ymin=c(-1,-1), xmax=c(1,2), ymax=c(1,1), col=c("blue", "red"), hovinf=c("rec1", "rec2")) 
ggp.test <- ggplot() + geom_rect(data=test.dat, aes(xmin=xmin, ymin=ymin, xmax=xmax, ymax=ymax, text=paste("hoverinfo:", hovinf)), fill=test.dat$col) + theme_bw() 

ply.test <- plotly_build(ggp.test) 
ply.test 

任何人可以解釋這種現象?

回答

1

它與您指定顏色的方式有關。由於您直接添加了fill參數,而沒有在aes之內添加,因此沒有任何美化將rects與eachother分開。 ggplot似乎自動覆蓋了這一點,但它沒有正確導出到plotly。當您將hovinf作爲textaes添加時,它可以使用該美學來區分反光板並能夠給它們適當的顏色。添加另一種審美也使它的工作,例如使用group

test.dat <- data.frame(xmin=c(0,1.5), ymin=c(-1,-1), xmax=c(1,2), ymax=c(1,1), col=c("blue", "red")) 
ggp.test <- ggplot() + geom_rect(data=test.dat, aes(xmin=xmin, ymin=ymin, xmax=xmax, ymax=ymax, group = col), fill=test.dat$col) + theme_bw() 
ggp.test 

ply.test <- plotly_build(ggp.test) 
ply.test 
+0

感謝您的簡單和明確的解釋!我現在可以看到問題出在哪裏。 –