繁体   English   中英

Matplotlib:y轴归一化

[英]Matplotlib: y-axis normalised

我有以下数据集

Date              Type        Label
2020-03-20         A            1
2020-03-20         A            0
2020-03-19         B            1
2020-03-17         A            1
2020-03-15         C            0
2020-03-19         A            0
2020-03-20         D            1
2020-03-20         A            1

我想 plot 在多行 plot 中使用归一化值。 下面的代码绘制了不同的时间线

import matplotlib.pyplot as plt

fig, ax = plt.subplots(1, figsize=[10,6])

(df.loc[df.Label.eq(1),].groupby(["Date","Type"]).agg({"Type":"count"})
 .unstack(1).droplevel(0,axis=1)
 .fillna(method="ffill")
 .plot(ax=ax, kind="line")
)

但是当我尝试应用标准化时

column_norm=['Type']
df[column_norm] = df[column_norm].apply(lambda x: (x - x.min()) / (x.max() - x.min()))

它失败了,返回一个错误:

TypeError: 不支持的操作数类型 -: 'str' 和 'str'

当我计算最小值和最大值时。

您能告诉我如何获得 y 轴归一化为 1 的 plot 吗?

根据少量数据样本以及您在共享的代码中使用countfillna的方式,我认为您希望计算计数标签的归一化/重新缩放后的累积总和等于 1。 以下是如何使用更大的样本数据集执行此操作的分步示例:

import numpy as np   # v 1.19.2
import pandas as pd  # v 1.1.3

# Create sample dataset
rng = np.random.default_rng(seed=1)  # random number generator
dti = pd.date_range('2020-01-01', '2020-01-31', freq='D')
size = 2*dti.size
dfraw = pd.DataFrame(data=dict(Type = rng.choice(list('ABCD'), size=size),
                               Label = rng.choice([0,1], size=size),
                               Date = rng.choice(dti, size=size)))
dfraw.head()

画法


您可以使用pivot_table方法简化 dataframe 的整形。 请注意df.Label.eq(1)掩码和聚合 function count如何在此处替换为aggfunc='sum' ,这利用了Label是数字的事实:

dfp = dfraw.pivot_table(values='Label', index='Date', columns='Type', aggfunc='sum')
dfp.head()

dfp


然后可以使用apply方法为每个变量计算归一化/重新缩放的累积和:

dfcs = dfp.apply(lambda x: x.cumsum()/x.sum(), axis=0)
dfcs.head()

dfcs


最后,可以填充 NaN 值,使 plot 中的行连续:

df = dfcs.fillna(method='ffill').fillna(value=0)
df.head()

df


ax = df.plot(figsize=(10,6))

# Format the tick labels using the default tick locations and format legend
ticks = ax.get_xticks()
ticklabels = pd.to_datetime(ticks, unit='D').strftime('%d-%b')
ax.set_xticks(ticks)
ax.set_xticklabels(ticklabels, rotation=0, ha='center')
ax.legend(title='Type', frameon=False);

pandas_line_plot

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM