【问题标题】:How can I plot a pandas dataframe so that one column is the color of each datapoint and another is the shape?如何绘制熊猫数据框,以便一列是每个数据点的颜色,另一列是形状?
【发布时间】:2017-10-09 03:09:25
【问题描述】:

我有一个带有日期的熊猫数据框(设置为索引)和一列总和计数,比如说,以及总和中涉及的两列分类标签(由原始数据框上的 groupby)。

如果可能的话,我想用对应于一列标签的标记/符号和对应于另一列标签的颜色/色调来绘制计数与时间的关系。所以它需要两个图例键。

例如:

Date        | Label1  | Label2  | Sum
------------|---------|---------|----
2017-01-01  | A       | X       | 380
2017-01-01  | B       | X       | 110
2017-01-02  | A       | X       | 247
2017-01-02  | B       | Y       | 278
2017-01-03  | A       | Y       | 357
2017-01-03  | B       | X       | 101
...

【问题讨论】:

    标签: python pandas matplotlib data-visualization seaborn


    【解决方案1】:

    好的,这个怎么样?

    from itertools import product
    
    # create your dataframe
    df = pd.DataFrame(
        columns=['Date', 'Label1', 'Label2', 'Sum'],
        data=[
            ['2017-01-01', 'A', 'X', 380],
            ['2017-01-01', 'B', 'X', 110],
            ['2017-01-02', 'A', 'X', 247],
            ['2017-01-02', 'B', 'Y', 278],
            ['2017-01-03', 'A', 'Y', 357],
            ['2017-01-03', 'B', 'X', 101]]
    ).set_index('Date')
    df.index = pd.DatetimeIndex(df.index)
    
    # create main axis
    ax = df.plot(y='Sum', style='.')
    
    # create masks
    A = df['Label1'] == 'A'
    B = df['Label1'] == 'B'
    X = df['Label2'] == 'X'
    Y = df['Label2'] == 'Y'
    
    # styles
    styles_colors = [
        (A, 'b'),  # blue
        (B, 'g'),  # green
    ]
    styles_shapes = [
        (X, '^'),  # triangle
        (Y, 'o'),  # circle
    ]
    
    # apply styles on subsets of the data (specified by the masks)
    for (mask1, style1), (mask2, style2) in product(styles_colors, styles_shapes):
        mask = mask1 & mask2
        style = style1 + style2
        df[mask].plot(y='Sum', ax=ax, style=style)
    

    【讨论】:

    • 谢谢 - 只是缺少我现在尝试自定义的图例。
    猜你喜欢
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    • 2017-12-08
    • 2021-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-25
    相关资源
    最近更新 更多