具有相同图例颜色和标签的堆叠子图

问题描述 投票:0回答:1

我一直在尝试绘制具有相同图例颜色和非重复标签的堆叠图,但没有取得太大成功。

from plotly.subplots import make_subplots

# Sample data
x = [1, 2, 3, 4, 5]
y1 = [1, 2, 4, 8, 16]
y2 = [1, 3, 6, 10, 15]
y3 = [1, 4, 8, 12, 16]

# Create subplot figure with two subplots
fig = make_subplots(rows=1, cols=2, subplot_titles=('Subplot 1', 'Subplot 2'))

# Add stacked area plot to subplot 1
fig.add_trace(go.Scatter(x=x, y=y1, mode='lines', stackgroup='one', name='A'), row=1, col=1)
fig.add_trace(go.Scatter(x=x, y=y2, mode='lines', stackgroup='one', name='B'), row=1, col=1)

# Add stacked area plot to subplot 2
fig.add_trace(go.Scatter(x=x, y=y1, mode='lines', stackgroup='two', name='A'), row=1, col=2)
fig.add_trace(go.Scatter(x=x, y=y3, mode='lines', stackgroup='two', name='C'), row=1, col=2)

# Update layout
fig.update_layout(title_text='Stacked Area Plots on Subplots', showlegend=True)

# Show figure
fig.show()

结果图如下:

如有任何帮助,我们将不胜感激。

python plotly
1个回答
0
投票

您可以直接为每条迹线设置填充颜色,如下所示:

from plotly.subplots import make_subplots
import plotly.graph_objects as go

# Sample data
x = [1, 2, 3, 4, 5]
y1 = [1, 2, 4, 8, 16]
y2 = [1, 3, 6, 10, 15]
y3 = [1, 4, 8, 12, 16]

# Create subplot figure with two subplots
fig = make_subplots(rows=1, cols=2, subplot_titles=('Subplot 1', 'Subplot 2'))

# Add stacked area plot to subplot 1
fig.add_trace(go.Scatter(x=x, y=y1, fillcolor="blue",mode='lines', stackgroup='one', name='A'), row=1, col=1)
fig.add_trace(go.Scatter(x=x, y=y2, fillcolor="red",mode='lines', stackgroup='one', name='B'), row=1, col=1)

# Add stacked area plot to subplot 2
fig.add_trace(go.Scatter(x=x, y=y1, fillcolor="blue", mode='lines', stackgroup='two', name='A'), row=1, col=2)
fig.add_trace(go.Scatter(x=x, y=y3, fillcolor="red", mode='lines', stackgroup='two', name='C'), row=1, col=2)

# Update layout
fig.update_layout(title_text='Stacked Area Plots on Subplots', showlegend=True)
# Show figure
fig.show(renderer="browser")

或者您可以按照[此处]所述进行映射。(https://community.plotly.com/t/automatically-pick-colors-when-using-add-trace/59075/2)

© www.soinside.com 2019 - 2024. All rights reserved.