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

时间:2016-12-15 02:16:41

标签: r ggplot2 plotly

使用从ggplot2扩展的ggplotly调用,我正在尝试为这些点添加大纲。

ggplot的调用有效,但将调用延伸至ggplotly会产生错误。

  

目标是根据带有黑色轮廓的连续变量(在这种情况下使用pch = 21)创建带有颜色填充点的交互式绘图。

最小可重复的例子:

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

enter image description here

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

1 个答案:

答案 0 :(得分:1)

你几乎就在那里,但是在+ggplotly()来电结束时ggplot()而不是标记,你需要用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)

虽然,我注意到在调用fill时没有尊重ggplotly ...

要直接在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)))

有关更多示例,请参阅herehere

enter image description here