如何绘制熊猫数据帧,以便一列是每个数据点的颜色,另一列是形状



我有一个带有日期(设置为索引(和一列求和计数的熊猫数据帧,例如,以及两列涉及求和的分类标签(通过原始数据帧上的分组(。

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

例如:

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
...
好吧,

这个怎么样?

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)

最新更新