【问题标题】:plotly converts ggplot2 colored rectangle to greyplotly 将 ggplot2 彩色矩形转换为灰色
【发布时间】:2017-02-14 09:53:26
【问题描述】:

我试图制作一个包含矩形的图。我正在使用 ggplot2 创建它们,并希望通过将它们转换为绘图对象来“使它们具有交互性”。 现在的问题是,转换为 plotly 似乎失去了 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

谁能解释这种现象?

【问题讨论】:

    标签: r ggplot2 plotly


    【解决方案1】:

    这与您指定颜色的方式有关。由于您是直接添加 fill 参数而不是在 aes 内部添加,因此没有将矩形彼此分开的美学。 ggplot 似乎自动涵盖了这一点,但它不能正确导出到 plotly。当您将hovinf 添加为text aes 时,它可以使用该美学来区分矩形并能够为它们提供适当的颜色。添加另一种美学也使它起作用,例如使用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
    

    【讨论】:

    • 感谢您简单明了的解释!我现在可以看到问题出在哪里了。
    猜你喜欢
    • 2011-12-28
    • 1970-01-01
    • 2016-01-11
    • 2015-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多