Search code examples
rplotlybackground-colorbubble-chart

Change the background colors of a bubble chart based on y axis values (using Plotly in R)


I created a bubble chart in R by using the Plotly package. I wish to change the background colors of some values on the y-axis. For example, in the graph below, it would be ideal to have 80-100 and 140-160 colored differently.

enter image description here

library(plotly)

data <- read.csv(
 "https://raw.githubusercontent.com/plotly/datasets/master/school_earnings.csv")

fig <- plot_ly(data, x = ~ Women, y = ~ Men, text = ~ School, 
             type = 'scatter', mode = 'markers', color = ~Gap, 
             colors = 'Reds',
             marker = list(size = ~ Gap, opacity = 0.5))
fig <- fig %>% layout(title = 'Gender Gap in Earnings per University',
         xaxis = list(showgrid = FALSE),
         yaxis = list(showgrid = FALSE))

fig

I wish to have the background colored like this:

enter image description here

I tried the paper_bgcolor, it seem to change the color of legend area instead of the background of the bubbles. Is there anyway to reach what I want?

library(plotly)

data <- read.csv(
  "https://raw.githubusercontent.com/plotly/datasets/master/school_earnings.csv")

fig <- plot_ly(data, x = ~ Women, y = ~ Men, text = ~ School, 
    type = 'scatter', mode = 'markers', color = ~ Gap, colors = 'Reds',
        marker = list(size = ~Gap, opacity = 0.5))
fig <- fig %>% layout(title = 'Gender Gap in Earnings per University',
         xaxis = list(showgrid = FALSE),
         yaxis = list(showgrid = FALSE),paper_bgcolor = "black")

fig

enter image description here


Solution

  • This can be done via the shapes command in layout, see https://plotly.com/r/shapes/.

    For your example, you could e.g. do

    library(plotly)
    
    data <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/school_earnings.csv")
    
    fig <- plot_ly(data, x = ~Women, y = ~Men, text = ~School, type = 'scatter', mode = 'markers', color = ~Gap, colors = 'Reds',
                   marker = list(size = ~Gap, opacity = 0.5))
    fig <- fig %>% layout(title = 'Gender Gap in Earnings per University',
                          xaxis = list(showgrid = FALSE),
                          yaxis = list(showgrid = FALSE))
    fig <- fig %>% layout(shapes = list(list(type = 'rect',fillcolor = 'green',line = list(color = 'green'),opacity = 0.3,
                                             x0 = 0,x1 = 1,xref = 'paper',y0 = 80,y1 = 100,yref = 'y'),
                                        list(type = 'rect',fillcolor = 'yellow',line = list(color = 'yellow'),opacity = 0.3,
                                             x0 = 0,x1 = 1,xref = 'paper',y0 = 140,y1 = 160,yref = 'y')))
    
    fig