首页 > 解决方案 > Pandas:使用 plotly 作为后端时如何选择绘图元素颜色?

问题描述

我正在尝试将Plotly 作为 pandas plot backend我按照这些说明成功配置了它,但是在配置图表元素颜色时遇到了麻烦。

这就是我想要做的。它使用 matplotlib 作为后端:

df.plot(kind='area', 
        color=['orange', 'lightslategray'],
        backend='matplotlib' )

正确的图表

但是当我尝试使用 ploty 时,它失败并出现一个奇怪的错误:

df.plot(kind='area', 
        color=['orange', 'lightslategray'], 
        backend='plotly' )

错误:

ValueError: All arguments should have the same length. The length of argument `color` is 2, whereas the length of  previously-processed arguments ['Dia', 'Alfa', 'Beta'] is 12

如果我不尝试设置任何颜色,该情节将起作用:

df.plot(kind='area', backend='plotly' )

情节错误的颜色

标签: pythonpandasplotplotlyplotly-python

解决方案


根据您的绘图后端,某些参数的含义似乎不同。color是其中之一。当使用 plotly 时,它会尝试选择一个将用作颜色的维度。正确的方法是使用color_discrete_map参数:

df.plot(kind='area', 
        color_discrete_map={
            'Alfa': 'orange', 
            'Beta': 'lightslategray'}, 
        backend='plotly' )

正确绘制

不幸的是,无法互换后端引擎。


推荐阅读