Strange formatting of legend in ggplotly in R

后端 未结 4 900
故里飘歌
故里飘歌 2020-12-11 20:53

I\'m trying to turn a ggplot into a plotly. The ggplot renders fine, but when I put it through ggplotly, suddenly the legend adds parenthesis and \",1\" after the label.

4条回答
  •  我在风中等你
    2020-12-11 21:10

    Here's an approach that worked for me. It involves diving into the resulting plotly object and cleaning up the legend names.

    The first part creates a function to detect if the plotly list element has a legend specified and then cleans it up.

    clean_plotly_leg <- function(.plotly_x, .extract_str) {
      # Inpects an x$data list in a plotly object, cleans up legend values where appropriate
      if ("legendgroup" %in% names(.plotly_x)) {
        # The list includes a legend group
    
        .plotly_x$legendgroup <- stringr::str_extract(.plotly_x$legendgroup, .extract_str)
        .plotly_x$name <- stringr::str_extract(.plotly_x$name, .extract_str)
    
      }
      .plotly_x
    
    
    }
    

    The second part applies it to your example, but with an intermediate step.

    sorted_plotly <-
      ggplotly(ggplot(sorted1, aes(x=as.Date(CommDate), y=PubB4))+
               geom_smooth(level=0.0, aes(colour="Moving average"), se=FALSE)+
               geom_point(aes(fill=CommName), size=4)+
               expand_limits(y=c(0,4.5))+
               geom_line(mapping=aes(y=4),colour="orangered3",size=1)+
               geom_text(mapping=aes(y=4.2, x=min(sorted1$CommDate)+4), label="Target", size=3)+
               xlab("Committee Date")+
               guides(fill=guide_legend(title="Committee Names"), colour=guide_legend(title.theme=element_blank(),title=NULL))+
               scale_x_date(labels = date_format("%b-%y"))+
               theme_light()+
               theme(plot.title=element_text(hjust=0.5, size=12),panel.grid.major.x = (element_blank()), 
                     panel.grid.minor.x = (element_blank()), 
                     axis.title = element_text(size=8), legend.title = element_text(size=10),
                     legend.text = element_text(size=8), legend.box = 'vertical', legend.spacing.y = unit(-2,"mm"))+
               scale_colour_manual(name="",values="#0072B2"))
    
    sorted_plotly$x$data <-
      sorted_plotly$x$data %>% 
      map(clean_plotly_leg, "[^\\(][^,]*") # ie remove the opening bracket, if one exists, and extract each character up to the first comma
    
    sorted_plotly 
    

    I'd welcome any suggestions for making this code more efficient, but at least it works

提交回复
热议问题