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

3

我刚接触Plotly,并尝试制作一些简单的图表。以下是一个简单的示例:

import plotly.graph_objects as go

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

fig.show()

这将导致: enter image description here 我想要更改背景网格颜色,使其在两种颜色之间交替显示,比如默认颜色和更深的灰色,以便柱形图更加清晰可见。我研究了fig.update_xaxes函数,但只能更改目前网格上为白色的线条颜色。
感谢任何帮助。
1个回答

4

从以下内容来看:

我正在研究fig.update_xaxes函数,但只能更改当前网格中的白色线条颜色。

听起来你实际上是在问如何更改沿y轴特定区段的背景颜色, 特别是因为你还说到:

[...]以便条形图更加清晰可见。

如果确实是这种情况,那么我会使用具有交替背景颜色的合理间隔的shapes,并将shapes设置为出现在图表的traces之后以获得如下效果:

enter image description here

如果你想隐藏网格线,你可以添加 xaxis=dict(showgrid=False):

enter image description here

完整代码:

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


谢谢,这真的很有帮助!我一定可以扩展这个代码到另一个轴。但希望有本地的方法来实现它,而不是用形状,不过这是一个好的解决方法。 - mlenthusiast
1
@codingenthusiast 很高兴能帮忙!如果您在将我的建议适用于其他目的方面遇到困难,请告诉我。 - vestland

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接