Reputation: 666
I was trying to make a plot containing rectangles. I am creating them with ggplot2 and would like to "make them interactive" by converting them to plotly objects. Now the problem is that the conversion to plotly seems to loose the rectangles colors specified in ggplot2.
Here is a small self-explaining code sample:
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
The funny thing is that when i specify hover information like below, then the colors are correct:
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
Can anybody explain this phenomena?
Upvotes: 1
Views: 365
Reputation: 1293
It has to do with the way you specify the colours. Since you're adding the fill
argument directly and not inside aes
there are no aesthetics that separate the rects from eachother. ggplot seems to cover this automatically, but it doesn't export properly to plotly. When you add hovinf
as the text
aes
it can use that aesthetic to differentiate the rects and is able to give them their appropriate colour. Adding another aesthetic also makes it work, for example using 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
Upvotes: 1