简体   繁体   中英

R ggplotly dublicated legend

I try to generate a plot on which every point stands for an event. Color, Size and faced_grid are used to give additional information available in a visual way. The graph is working in ggplot2 but it is often important to know the exact numbers so an interactive version is needed which enables to hover over the point and get the info. I tried to convert the plot into an interactive version with the function ggplotly from the plotly-package. The problem then is, that the legend not only display the different states of the used attributes, it contains every existent combination. In addition, it did not display info from geom_rect.

I found related/similar questions but they used the function plot_ly and not ggploty or did not provide an answer.

Following, the same problem illustrated with the mtcars dataset:

library(plotly)

g = ggplot(mtcars,aes(x=mpg,y=disp,color = as.factor(cyl),size =as.factor(gear))) +
    geom_point() +
    geom_text(label = c(rep("A",nrow(mtcars)-5),rep("B",5)),color = "black",size=4) +
    geom_rect(data=data.frame(name="zone",Start=20,End = 30,ymin = -Inf,ymax = Inf),aes(xmin=Start, xmax=End, ymin=ymin, ymax=ymax,fill=name),inherit.aes = FALSE,alpha=0.3)+
    facet_grid(vs~am)
g

This is the result and how it should look like: ggplot Graph

Now using ggplotly

ggplotly(g)

This is the result: ggploty Graph

(1) The legend is now a combination of the different attributes used for Color and Size

(2) geom_rect is in the legend but didn't get displayed in the graph

Does anyone knows how to get the same graph in ggplotly like in ggplot2? I am grateful for every hint. Thanks

Dave

I do not know how to fix the combination of legends when you use ggplotly. But, I can fix the second problem, if you do not use the Inf and -Inf, the geom_rect will work:

ggplotly(ggplot(mtcars,aes(x=mpg,y=disp, = as.factor(cyl),size =as.factor(gear))) +
             geom_rect(aes( xmin=20, 
                            xmax=30, 
                            ymin=0, 
                            ymax=max(mtcars$disp),
                            fill="Name"),
                       inherit.aes = FALSE, alpha=0.3) +
             geom_point() +
             geom_text(label = c(rep("A",nrow(mtcars)-5),rep("B",5)), = "black",size=4) +
             facet_grid(vs~am)) 

However, the legends are bad. I would suggest using subplot to create the same thing in Plotly, and I think this link Ben mentioned will help you create each subplot. One thing to mention is that I had trouble Illustrating different size in legend in plotly, while the size of the marker will be different, there will not be a legend for the size scale. Maybe a scale will be a better option.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM