plotly 将 ggplot2 彩色矩形转换为灰色
plotly converts ggplot2 colored rectangle to grey
我试图绘制一个包含矩形的图。我正在使用 ggplot2 创建它们,并希望通过将它们转换为 plotly 对象来 "make them interactive"。
现在的问题是,转换为 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
谁能解释一下这种现象?
这与您指定颜色的方式有关。由于您是直接添加 fill
参数而不是在 aes
内部添加参数,因此没有将 rects 彼此分开的美学。 ggplot 似乎自动涵盖了这一点,但它无法正确导出到 plotly。当您将 hovinf
添加为 text
aes
时,它可以使用该美学来区分 rects 并能够为它们提供适当的颜色。添加另一种美学也可以使其起作用,例如使用 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
我试图绘制一个包含矩形的图。我正在使用 ggplot2 创建它们,并希望通过将它们转换为 plotly 对象来 "make them interactive"。 现在的问题是,转换为 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
谁能解释一下这种现象?
这与您指定颜色的方式有关。由于您是直接添加 fill
参数而不是在 aes
内部添加参数,因此没有将 rects 彼此分开的美学。 ggplot 似乎自动涵盖了这一点,但它无法正确导出到 plotly。当您将 hovinf
添加为 text
aes
时,它可以使用该美学来区分 rects 并能够为它们提供适当的颜色。添加另一种美学也可以使其起作用,例如使用 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