Search code examples
rplotly

Is there a way to add text to the `y2` axis of a plotly chart in R?


I would like to add text to the data points in a plotly chart. See the example below:

df <- data.frame(
  category_value = c("A", "B", "C"), 
  bar_value = c(1000, 2000, 15000), 
  line_value = c(0.8, 0.9, 0.7)
)


plot_ly(df) %>%
  add_trace(x = ~category_value, y = ~bar_value, type = "bar", name = "bar_value") %>%
  add_trace(x = ~category_value, y = ~line_value, yaxis = "y2", type = "scatter", name = "line_value", mode = "lines+markers") %>%
  layout(xaxis = list(title = var), yaxis2 = list(overlaying = "y", side = "right")) %>% 
  add_text(x = ~category_value, y = ~bar_value, text = ~bar_value, textposition = "top right") %>% 
  add_text(x = ~category_value, y = ~line_value, text = ~line_value, textposition = "top right")

The problem is that the text for the line chart is too low in the y-dimension. Something like add_text(x = ~category_value, y2 = ~line_value, text = ~line_value, textposition = "top right") would be helpful, but this does not work.


Solution

  • Yes, for sure. If you wanted the text labels for the bars and lines, you don't need four traces, you only need two (Plotly will make the rest.) Instead of "lines+markers" you can use "lines+markers+text", for the bar chart, you simply need to add the argument text.

    I moved the legend over as well. The legend was overlapping the axis ticks for y2.

    plot_ly(df) %>%
      add_trace(x = ~category_value, y = ~bar_value, type = "bar", name = "bar_value",
                text = ~bar_value, hoverinfo = "x+y", textposition = "top") %>%
      add_trace(x = ~category_value, y = ~line_value, yaxis = "y2", text = ~line_value,
                type = "scatter", name = "line_value", mode = "lines+markers+text",
                textposition = "top") %>%
      layout(xaxis = list(title = var), 
             yaxis2 = list(overlaying = "y", side = "right"),
             legend = list(x = 1.05))
    

    enter image description here