Plotly:如何交替背景网格颜色?

Plotly: How to alternate background grid color?

我对 Plotly 还很陌生,正在尝试一些简单的图表。我有这个简单的例子:

import plotly.graph_objects as go

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

fig.show()

结果是:

我想更改背景网格颜色以在两种颜色之间交替,比方说默认颜色和较深的灰色,以便条形更明显。我正在查看 fig.update_xaxes 函数,但只能更改当前网格上白色线条的颜色。

感谢任何帮助。

判断依据:

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.

听起来您实际上是在询问如何更改 背景颜色 沿 y 轴的特定背景部分.特别是因为你还说:

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

如果事实确实如此,那么我将使用具有交替背景颜色的合理间隔的形状,并将形状设置为出现"below"(在图形的痕迹后面)得到这个:

如果您想隐藏网格线,您只需将 xaxis=dict(showgrid=False) 加入混合即可:

完整代码:

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()