mfindinge
mfindinge

Reputation: 177

R plotly draw in label zone

Is it possible to plot shapes below the x-"label axis". E.g for:

h <- mtcars %>% group_by(gear) %>% summarise(mpg = mean(mpg))
plot_ly(
  h, name = "20", type = "waterfall", 
  x = ~gear,
  textposition = "outside", 
  text = c("Gear 3", "Gear 4", "Gear 5"),
  y= ~mpg)

To have red boxes like below. Ideally I would want those boxes to be aligned with eachother and the above boxes, but my paint skills are non-existing.

enter image description here

Thank you.

Upvotes: 1

Views: 189

Answers (1)

stefan
stefan

Reputation: 125028

You can use add_annotations to place boxes outside of the plotting area. After some trial and error:

  1. Set yref = "paper"

  2. Set y = 0. (Aligns the boxes with the x-axis)

  3. Shift the boxes using yshift = -xxxx. (Shifts the boxes outside)

  4. Increase the bottom margin using layout(margin = list(b = xxxx)) (Makes space for the boxes)

Try this:

library(plotly)

h <- mtcars %>% group_by(gear) %>% summarise(mpg = mean(mpg))
plot_ly(
  h, name = "20", type = "waterfall", 
  x = ~gear,
  textposition = "outside", 
  text = c("Gear 3", "Gear 4", "Gear 5"),
  y= ~mpg) %>% 
  add_annotations(
    x = ~gear,
    y = 0,
    yshift = -100,
    bgcolor = I("red"),
    bordercolor = I("black"),
    width = 200,
    height = 20,
    yref = "paper",
    text = c("Gear 3", "Gear 4", "Gear 5"),
    showarrow = FALSE
  ) %>% 
  layout(margin = list(b = 100))

enter image description here

Upvotes: 1

Related Questions