如何绘制 pandas 数据框,以便一列是每个数据点的颜色,另一列是形状?
How can I plot a pandas dataframe so that one column is the color of each datapoint and another is the shape?
我有一个 pandas 数据框,其中包含日期(设置为索引)和一列求和计数,以及两列参与求和的分类标签(通过原始数据框上的 groupby)。
我想根据时间绘制计数,markers/symbols 对应一列标签,color/hue 对应另一列标签,如果可能的话。所以它需要两个图例键。
例如:
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)
我有一个 pandas 数据框,其中包含日期(设置为索引)和一列求和计数,以及两列参与求和的分类标签(通过原始数据框上的 groupby)。
我想根据时间绘制计数,markers/symbols 对应一列标签,color/hue 对应另一列标签,如果可能的话。所以它需要两个图例键。
例如:
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)