首页 > 解决方案 > 在 Python Plotly 中按类别组绘制

问题描述

我有一个只有 5 个变量的熊猫数据框。我想通过分类变量创建散点图和颜色。我正在使用情节,所以我可以放大到特定区域。Plotly 不允许我将分类变量列表作为颜色传递。先感谢您!这是我的代码:

import plotly.graph_objs as go
import plotly.plotly as py
import plotly.tools

plotly.tools.set_credentials_file(username='user', api_key='key')

trace1 = go.Scatter(
    x = df['var1'],
    y = df['var2'],
    mode='markers',
    marker=dict(
        size=16,
        color = df['categorialVar'], #set color equal to a variable
        showscale=True
    )
)
data = [trace1]

py.iplot(data, filename='scatter-plot-with-colorscale')

标签: pythonpython-3.xplotly

解决方案


最近遇到这个问题,做了一个解决方案:

def get_random_qualitative_color_map(
        categorial_series: pd.Series,
        colors: typing.List[str] = plotly_colors.qualitative.Alphabet
) -> typing.List[str]:
    """
    Returns a color coding for a given series (one color for every unique value). Will repeat colors if not enough are
    provided.
    :param categorial_series: A series of categorial data
    :param colors: color codes (everything plotly accepts)
    :return: Array of colors matching the index of the objects
    """
    # get unique identifiers
    unique_series = categorial_series.unique()

    # create lookup table - colors will be repeated if not enough
    color_lookup_table = dict((value, color) for (value, color) in zip(unique_series, itertools.cycle(colors)))

    # look up the colors in the table
    return [color_lookup_table[key] for key in categorial_series]
  • 如果颜色数组为空,则解决方案重复颜色
  • 可以与任何调色板一起使用(在这种情况下 plot.ly 字母是默认值)

解释

unique_series = categorial_series.unique()

首先我们得到系列中的唯一值。他们每个人都将匹配一种颜色。

color_lookup_table = dict((value, color) for (value, color) in zip(unique_series, itertools.cycle(colors)))

接下来我们将创建一个 dict ( 函数作为查找表 - 我们可以查找哪个颜色属于哪个类别元素。这里的棘手部分是使用itertools.cycle(colors)。这个函数将返回一个迭代器,它将始终循环给定的所有值可迭代的(在这种情况下是 plot.ly 定义的颜色列表)。

接下来我们将zip使用这个迭代器和实际的独特项目。这会创建成对的 (unique_item, color)。我们得到了永远不会用完颜色的好效果(因为循环迭代器将无休止地运行)。这意味着返回的 dict 将包含len(unique_series)项目。

[color_lookup_table[key] for key in categorial_series]

最后,我们使用列表推导在查找表中查找系列中的每个条目。这将为数据点创建一个颜色列表。然后可以将该列表用作colorany 中标记 dict 中的参数的参数plotly.graphics_object


推荐阅读