如何绘制一个pandas数据框,以便一列是每个数据点的颜色,另一列是形状?

时间:2017-05-10 12:47:33

标签: python pandas matplotlib data-visualization seaborn

我有一个带有日期(设置为索引)的pandas数据框和一个总和计数列,比如和总和中涉及的两列分类标签(通过原始数据帧上的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
...

1 个答案:

答案 0 :(得分:0)

好的,这个怎么样?

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)