2
votes

I'm very new to Plotly and trying out some simple graphs. I have this simple example:

import plotly.graph_objects as go

fig = go.Figure(go.Bar(
            x=[20, 14, 23],
            y=['giraffes', 'orangutans', 'monkeys'],
            orientation='h'))

fig.show()

Which results in: enter image description here

I would like to change the background grid color to alternate between two colors, let's say the default color and a darker gray color so that the bars are more visible. I was looking into the fig.update_xaxes function but was only able to change the colors of the lines which are white currently on the grid.

Any help is appreciated.

1

1 Answers

3
votes

Judging from:

I was looking into the fig.update_xaxes function but was only able to change the colors of the lines which are white currently on the grid.

It sounds like you're actually asking how to change the background color for particular segments of the background along the y-axis. Particularly since you're also stating that:

[...] so that the bars are more visible.

If that is in fact the case, then I would use shapes for sensible intervals with alternating background colors, and set the shapes to appear "below" (behind) the traces of the figure to get this:

enter image description here

And if you'd like to hide the gridlines you can just throw xaxis=dict(showgrid=False) into the mix:

enter image description here

Complete code:

import plotly.graph_objects as go
import numpy as np

y = ['giraffes', 'orangutans', 'monkeys']
x = [20, 14, 23]
fig = go.Figure(go.Bar(
            x=x,
            y=y,
            orientation='h'))

# find step size for an interval for the number of y-values
steps = 1/len(y)

# set up where each interval ends
ends = [0 + steps*(e+1) for e in np.arange(0, len(y))]

# container for shapes to be added as backgrounds
shapes = []
# super-easy way of making a list for alternating backgrounds
colors = ['grey', 'rgba(0,0,0,0)']*len(y)

# set up shapes for alternating background colors
for i, e in enumerate(ends):
        shapes.append(dict(type="rect",
                        xref="paper",
                        yref="paper",
                        x0=0,
                        y0=e-steps,
                        x1=1,
                        y1=e,
                        fillcolor=colors[i],
                        opacity=0.5,
                        layer="below",
                        line_width=0,
        )
    )
# fig.update_layout(xaxis=dict(showgrid=True), shapes=shapes)
# fig.show()
fig.update_layout(xaxis=dict(showgrid=False), shapes=shapes)
fig.show()

enter image description here