【问题标题】:How to use a colorscale palette with plotly and python?如何在 plotly 和 python 中使用色阶调色板?
【发布时间】:2019-03-05 19:40:50
【问题描述】:

我正在尝试更改我在 python 中使用 plotly 和 cufflinks 绘制的堆栈条形图的颜色(cufflinks 库允许直接从数据帧中绘制图表,这非常有用)。

我们看下图(我用的是jupyter notebook):

import plotly.plotly as py
import cufflinks as cf

cf.set_config_file(offline=True, world_readable=True, theme='white')

df = pd.DataFrame(np.random.rand(10, 4), columns=['A', 'B', 'C', 'D'])
df.iplot(kind='bar', barmode='stack')

如何使用上述代码实现新的调色板?我想使用“Viridis”调色板。我还没有找到一种方法来修改图形的颜色或使用调色板自动为条形图的不同堆栈着色。你们中有人知道怎么做吗?

非常感谢您的帮助,

【问题讨论】:

    标签: python pandas colors plotly


    【解决方案1】:
    trace0 = go.Scatter(
        x = foo,
        y = bar,
        name = 'baz',
        line = dict(
            color = ('rgb(6, 12, 24)'),
            width = 4)
    )
    

    这允许您更改线条的颜色,或者您可以使用

    colors = `['rgb(67,67,67)', 'rgb(115,115,115)', 'rgb(49,130,189)', 'rgb(189,189,189)']`
    

    用于图表的单独线条。要使用指定的颜色渐变试试

    data = [
        go.Scatter(
            y=[1, 1, 1, 1, 1],
            marker=dict(
                size=12,
                cmax=4,
                cmin=0,
                color=[0, 1, 2, 3, 4],
                colorbar=dict(
                    title='Colorbar'
                ),
                colorscale='Viridis'
            ),
            mode='markers')
    ]
    

    【讨论】:

    • 感谢您的帮助,但我不明白如何从我的 3 行代码转到您所说的内容。
    • 尝试 colorscale='Viridis'
    • @Peslier53,我建议您查看文档here。您可以找到如何绘制基本条形图,如何指定datatracelayout。了解后可以设置colorscaletitle等。
    【解决方案2】:

    找到了我的问题的答案:

    import plotly.plotly as py
    import cufflinks as cf
    from bokeh.palettes import viridis
    
    cf.set_config_file(offline=True, world_readable=True, theme='white')
    colors = viridis(4)
    df = pd.DataFrame(np.random.rand(10, 4), columns=['A', 'B', 'C', 'D'])
    fig = df.iplot(kind='bar', barmode='stack',asFigure = True)
    
    for i,color in enumerate(colors):
        fig['data'][i]['marker'].update({'color': color})
        fig['data'][i]['marker']['line'].update({'color': color})
    
    py.offline.iplot(fig)
    

    【讨论】:

      【解决方案3】:

      以@Peslier53 的回答为基础: 您可以直接在 df.iplot() 中指定颜色或色阶:

      import plotly.plotly as py
      import cufflinks as cf
      from bokeh.palettes import viridis
      
      cf.set_config_file(offline=True, world_readable=True, theme='white')
      colors = viridis(4)
      df = pd.DataFrame(np.random.rand(10, 4), columns=['A', 'B', 'C', 'D'])
      df.iplot(kind='bar', barmode='stack', colors = colors)
      
      

      这为您节省了几行代码并使绘图变得非常方便。 它也适用于任何颜色列表(例如,根据图表类型,热图需要颜色渐变而不是颜色列表),因此您也可以使用自定义颜色。

      【讨论】:

        猜你喜欢
        • 2019-11-21
        • 2022-07-13
        • 1970-01-01
        • 1970-01-01
        • 2020-09-05
        • 1970-01-01
        • 1970-01-01
        • 2018-08-25
        • 2021-12-20
        相关资源
        最近更新 更多