2017-02-14 60 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

感谢您的简单和明确的解释!我现在可以看到问题出在哪里。 –