1

I am trying to create an interactive plot with a ggplot object via ggplotly. The ggplot plots fine but ggplotly removes the superscript from the legend and also the caption of the plot.

How can I fix this?

    library(tidyverse)
    library(plotly)
    
        # df
        Pollutant_1 = c(2.5, 3.5, 1.5, 7.5)
        Pollutant_2 = c(4, 1.3, 2.5, 3.5)
        Year = c(2000, 2001, 2004, 2003)
        
        df = data.frame(Year , Pollutant_1,  Pollutant_2)
        
            # Plot 
            # Make a legend vector
            legend = expression(Pollutant_1~"(ug/m)"^{3},
                                      Pollutant ~"Matter 2.5 (ug/m)"^3)
            
            gg = ggplot(df, aes(x = Year)) +
              geom_line(aes(y = Pollutant_1, color = Pollutant_1),size = 1) +
              geom_point(aes(y = Pollutant_1)) +
              scale_color_discrete(labels = legend) +
              geom_line(aes(y = Pollutant_2, color = Pollutant_2), size = 1) +
              geom_point(aes(y = Pollutant_2)) +
                               labs(x = "Date",
                                    y = "Concentration", 
                                    title = "Title",
                                    color = "Legend",
                                    caption = str_wrap("big caption."))

# Interactive 
ggplotly(gg)
Ed_Gravy
  • 1,841
  • 2
  • 11
  • 34

1 Answers1

2

This is a known issue.

One workaround for short captions is found here: plotly adding a source or caption to a chart. For the (MANY) plotly annotation options see this documentation.

For longer captions, you'll need to set up some margins to write in. Instructions here: Python: Create annotation space above the graph in Plotly

Would love to know if someone has a better approach.

Martina
  • 158
  • 8