如何使用颜色填充解决 ggplotly 错误

How to resolve ggplotly error using color fill

使用从 ggplot2 扩展的 ggplotly 调用,我正在尝试为点添加轮廓。

ggplot 的调用有效,但将调用扩展到 ggplotly 会产生错误。

The objective is the have an interactive plot with color filled points based on a continuous variable with a black outline (using pch=21 in this case).

最小可重现示例:

library(ggplot2)
library(plotly)
ggplot(data=mtcars, aes(mpg, wt, fill=hp))+geom_point(pch=I(21))+scale_fill_continuous(low='red', high='blue')

ggplot(data=mtcars, aes(mpg, wt, fill=hp))+geom_point(pch=I(21))+scale_fill_continuous(low='red', high='blue')+ggplotly()

Error: Don't know how to add o to a plot In addition: Warning message: In L$marker$color[idx] <- aes2plotly(data, params, "fill")[idx] : number of items to replace is not a multiple of replacement length

您就快完成了,但是您需要在 ggplot 周围加上 ggplotly[,而不是在 ggplot() 调用结束时标记 +ggplotly()

## save the ggplot object 
g <- ggplot(data=mtcars, aes(mpg, wt, fill=hp))+
    geom_point(pch=I(21))+
    scale_fill_continuous(low='red', high='blue')

## call ggplotly on the ggplot object
ggplotly(g)

尽管如此,我注意到在调用 ggplotlyfill 没有得到遵守...

要直接在 plot_ly 中执行此操作,您可以指定一个调色板并绘制它

pal <- colorRampPalette(c("red","blue"))(length(unique(mtcars$hp)))

plot_ly(data = mtcars, x = ~mpg, y = ~wt, color = ~hp, colors = pal, 
            type = "scatter", mode = "markers",
            marker = list(size = 10,
                          line = list(color = "black",
                          width = 2)))

有关更多示例,请参阅 here and here