Plotly:如何在两个子图上使用相同的配色方案?

2022-01-21 00:00:00 python plotly

问题描述

我正在尝试使用 plotly 绘制两个散点图,其中两个子图中自动选择的颜色相同,但我找不到这样做的方法.

I am trying to plot two scatter subplots with plotly whereby the colour automatically chosen in the two sub-plots is the same, but I cannot find a way to do so.

以下是代码片段:

import plotly as py
import plotly.tools as to
import numpy as np
import plotly.graph_objs as go
fig=to.make_subplots(rows=1,cols=2,subplot_titles=['Plot 1','Plot 2'])
X=[0,50,100,150,200,250,300,350,400,450,500]
Y=[1,2,3,4,5,6,7,8,9,10,11]
Z=Y.copy()
for i  in np.arange(11):
    if i==0:
            Z[0]=Y[0]
    else:
            Z[i]=Y[i]+Z[i-1]
trace=go.Scatter(x=X,y=Y)
fig.append_trace(trace,1,1)
trace=go.Scatter(x=X,y=Z,showlegend=False)
fig.append_trace(trace,1,2);
py.offline.plot(fig)

上面的代码绘制了两个子图,散点图将具有不同的颜色.我希望它们具有相同的颜色.我知道我可以对两个散点图上的颜色进行硬编码,但我需要从某个配色方案中自动选择颜色.

The above code plots two subplots and the scatters will have a different colour. I want them to have the same colour. I am aware that I can hard-code the colour on the two scatters but I need the colours to be selected automatically from some colour scheme.

我怎样才能达到我的需要?

How can I achieve what I need?


解决方案

以下建议使用plotly版本4.2.0,但颜色的处理方式应该相同.

The following suggestion uses plotly version 4.2.0, but the approach regarding the colors should be the same.

您可以使用以下方法在子图中的标记中设置线条的颜色:

You can set the color of your lines in markers in your subplots using:

line=dict(width=2, color=cols[0])
marker=dict(color=cols[1])

如果您想使用某种配色方案,您可以使用以下方法选择默认的绘图颜色:

If you'd like to work with a certain color scheme you can pick up the default plotly colors using:

#in:
import plotly
cols = plotly.colors.DEFAULT_PLOTLY_COLORS

#out:
['rgb(31, 119, 180)',
 'rgb(255, 127, 14)',
 'rgb(44, 160, 44)',
 'rgb(214, 39, 40)',
 'rgb(148, 103, 189)',
 'rgb(140, 86, 75)',
 'rgb(227, 119, 194)',
 'rgb(127, 127, 127)',
 'rgb(188, 189, 34)',
 'rgb(23, 190, 207)']

这是一个示例,它在线条上使用来自相同配色方案的相同颜色,而在标记上使用稍微不同的颜色.

Here's an example that uses the same colors from the same color scheme on the lines, and a bit different colors on the markers.

剧情:

代码:

# imports
from plotly.subplots import make_subplots
import plotly.graph_objs as go
import pandas as pd
import numpy as np
import plotly

cols = plotly.colors.DEFAULT_PLOTLY_COLORS


fig=make_subplots(rows=1,cols=2,subplot_titles=['Plot 1','Plot 2'])
X=[0,50,100,150,200,250,300,350,400,450,500]
Y=[1,2,3,4,5,6,7,8,9,10,11]
Z=Y.copy()
for i  in np.arange(11):
    if i==0:
            Z[0]=Y[0]
    else:
            Z[i]=Y[i]+Z[i-1]
trace=go.Scatter(x=X,
                 y=Y,
                 line=dict(width=2, color=cols[0]),
                 marker=dict(color=cols[1]),
                 showlegend=False
                )
fig.append_trace(trace,1,1)

trace=go.Scatter(x=X,
                 y=Z,
                 line=dict(width=2, color=cols[0]),
                 marker=dict(color=cols[7]),
                 showlegend=False)

fig.append_trace(trace,1,2)

fig.show()

相关文章