0

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

image

UseR10085
  • 7,120
  • 3
  • 24
  • 54
brian
  • 75
  • 1
  • 8

1 Answers1

0

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

enter image description here

UseR10085
  • 7,120
  • 3
  • 24
  • 54
  • 1
    It is not working. Does the column structure such as character/factor affect the labelling? – brian Oct 13 '20 at 07:58
  • Without your data, it is very hard to figure it out. Please provide your data in `dput()` format. – UseR10085 Oct 13 '20 at 08:40
  • 1
    This example with the `iris` dataset no longer works; the legend entries still say "setosa", "versicolor", etc. – jrcalabrese Jan 07 '23 at 16:16