matplotlib 如何在x轴上使用www.example.com创建pandas密度图datetime.date

f2uvfpb9  于 2023-05-29  发布在  其他
关注(0)|答案(1)|浏览(105)
#dataframe
a=
timestamp      count
2021-08-16     20
2021-08-17     60
2021-08-18     35
2021-08-19      1
2021-08-20      0
2021-08-21      1
2021-08-22     50
2021-08-23     36
2021-08-24     68
2021-08-25    125
2021-08-26     54

I applied this code
a.plot(kind="density")

这不是我想要的。

我想把Count放在Y轴上,timestamp放在X轴上,用密度绘图。
就像我可以用plt.bar(a['timestamp'],a['count'])做一样
或者这是不可能的密度绘图?

oknwwptz

oknwwptz1#

下面的代码创建密度直方图。假设每个时间戳计为1个单位,则总面积总和为1。为了获得x轴的时间戳,它们被设置为索引。要使总面积总和为1,所有计数值除以其总和。
从相同的数据计算的kde a。

from matplotlib import pyplot as plt
import pandas as pd
import numpy as np
from scipy.stats import gaussian_kde
from io import StringIO

a_str = '''timestamp      count
2021-08-16     20
2021-08-17     60
2021-08-18     35
2021-08-19      1
2021-08-20      0
2021-08-21      1
2021-08-22     50
2021-08-23     36
2021-08-24     68
2021-08-25    125
2021-08-26     54'''
a = pd.read_csv(StringIO(a_str), delim_whitespace=True)

ax = (a.set_index('timestamp') / a['count'].sum()).plot.bar(width=0.9, rot=0, figsize=(12, 5))

kde = gaussian_kde(np.arange(len(a)), bw_method=0.2, weights=a['count'])

xs = np.linspace(-1, len(a), 200)
ax.plot(xs, kde(xs), lw=2, color='crimson', label='kde')
ax.set_xlim(xs[0], xs[-1])
ax.legend(labels=['kde', 'density histogram'])
ax.set_xlabel('')
ax.set_ylabel('density')
plt.tight_layout()
plt.show()

如果你只想绘制kde曲线,你可以省略直方图。也可以填充曲线下的区域。

fig, ax = plt.subplots(figsize=(12, 5))

kde = gaussian_kde(np.arange(len(a)), bw_method=0.2, weights=a['count'])

xs = np.linspace(-1, len(a), 200)
# plot the kde curve
ax.plot(xs, kde(xs), lw=2, color='crimson', label='kernel density estimation')
# optionally fill the area below the curve
ax.fill_between(xs, kde(xs), color='crimson', alpha=0.2)
ax.set_xticks(np.arange(len(a)))
ax.set_xticklabels(a['timestamp'])
ax.set_xlim(xs[0], xs[-1])
ax.set_ylim(ymin=0)
ax.legend()
ax.set_xlabel('')
ax.set_ylabel('density')
plt.tight_layout()
plt.show()

要绘制多条类似的曲线,例如使用更多的count列,可以使用循环。可以从Set2颜色Map图中获得一个很好地搭配在一起的颜色列表:

from matplotlib import pyplot as plt
import pandas as pd
import numpy as np
from scipy.stats import gaussian_kde

a = pd.DataFrame({'timestamp': ['2021-08-16', '2021-08-17', '2021-08-18', '2021-08-19', '2021-08-20', '2021-08-21',
                                '2021-08-22', '2021-08-23', '2021-08-24', '2021-08-25', '2021-08-26']})
for i in range(1, 5):
    a[f'count{i}'] = (np.random.uniform(0, 12, len(a)) ** 2).astype(int)

xs = np.linspace(-1, len(a), 200)
fig, ax = plt.subplots(figsize=(12, 4))
for column, color in zip(a.columns[1:], plt.cm.Set2.colors):
    kde = gaussian_kde(np.arange(len(a)), bw_method=0.2, weights=a[column])
    ax.plot(xs, kde(xs), lw=2, color=color, label=f"kde of '{column}'")
    ax.fill_between(xs, kde(xs), color=color, alpha=0.2)
    ax.set_xlim(xs[0], xs[-1])
ax.set_xticks(np.arange(len(a)))
ax.set_xticklabels(a['timestamp'])
ax.set_xlim(xs[0], xs[-1])
ax.set_ylim(ymin=0)
ax.legend()
ax.set_xlabel('Date')
ax.set_ylabel('Density of Counts')
plt.tight_layout()
plt.show()

相关问题