简体   繁体   中英

Renaming legend text in ggplotly

I have integrated my ggplot code into ggplotly but the scale_manual_color() for renaming the legend texts isn't recognised by ggplotly.

ggplotly(
  ggplot(data = national2,aes(x=period, y=pregnancy))+
    geom_line(aes(color=type),size=0.8)+
    scale_color_manual(values=c("red","blue","green"),
                       breaks = c("pregnancy1019","pregnancy1519","pregnancy1014"),
                       labels=c("Teen pregnancy (10-19years)","Teen pregnancy (15-19years)","Teen pregnancy (10-14years)"))+
    labs(
      title = "Teen pregnancy trends from 2016Q1 to 2020Q2",
      x="Yearly quarters",
      y="Teen pregnancies"

    )+
    scale_x_yearqtr(n=10)+
    theme_gray()+
    theme(
      plot.title = element_text(size = 14),
      legend.title = element_blank(),
      legend.text = element_text(size = 12),
      axis.title = element_text(face = "bold",size = 11),
      axis.text = element_text(face = "bold",size = 10)
  )

图片

You have not provided any data, so, I am using iris dataset. Just remove breaks = c("pregnancy1019","pregnancy1519","pregnancy1014"), part from your code, it will run perfectly.

library(plotly)

ggplotly(
  ggplot(data = iris,aes(x=Sepal.Length, y=Petal.Width, color=Species))+
    geom_line(size=0.8)+
    scale_color_manual(values=c("red","blue","green"),
                       #breaks = c("pregnancy1019","pregnancy1519","pregnancy1014"),
                       labels=c("Teen pregnancy (10-19years)","Teen pregnancy (15-19years)","Teen pregnancy (10-14years)"))+
    labs(
      title = "Teen pregnancy trends from 2016Q1 to 2020Q2",
      x="Yearly quarters",
      y="Teen pregnancies"
      
    )+
    #scale_x_yearqtr(n=10)+
    theme_gray()+
    theme(
      plot.title = element_text(size = 14),
      legend.title = element_blank(),
      legend.text = element_text(size = 12),
      axis.title = element_text(face = "bold",size = 11),
      axis.text = element_text(face = "bold",size = 10)
    )

在此处输入图片说明

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