How to resolve ggplotly error using color fill

2019-07-22 07:13发布

Using the ggplotly call extending from ggplot2, I'm trying to add an outline to the points.

The call to ggplot works, but extending the call to ggplotly yields an error.

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).

Minimal reproducible example:

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

标签: r ggplot2 plotly
1条回答
劫难
2楼-- · 2019-07-22 07:31

You're almost there, but instead of tagging on +ggplotly() on the end of the ggplot() call, you need to surround the ggplot with 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)

Although, I am noticing that the fill isn't respected when calling ggplotly...

To do this directly in plot_ly, you can specify a colour palette and plot it

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)))

See here and here for more examples

enter image description here

查看更多
登录 后发表回答