python - 平滑绘制数据框的所有列

标签 python pandas plot smoothing

我有一个数据框:

Index   Date        AA   BB   CC     DD    EE   FF
0       2019-01-15  0.0  -1.0  0.0   0.0   0.0  2.0
1       2019-01-17  0.0  -1.0  -1.0  -1.0  0.0  2.0
2       2019-01-22  1.0  -1.0  1.0   -1.0  0.0  2.0
3       2019-01-24  0.0  0.0   0.0   0.0   0.0  2.0
4       2019-01-29  1.0  0.0   -1.0  0.0   -1.0 2.0
5       2019-01-31  0.0  -1.0  0.0   0.0   0.0  2.0
6       2019-02-05  1.0  1.0   1.0   0.0   1.0  2.0
7       2019-02-12  2.0  1.0   1.0   0.0   2.0  2.0

我正在策划:

dfs = dfs.melt('Date', var_name = 'cols', value_name = 'vals')
ax = sns.lineplot(x = "Date", y = 'vals', hue = 'cols', 
                  style = 'cols', markers = True, dashes = False, data = dfs)
ax.set_xticklabels(dfs['Date'].dt.strftime('%d-%m-%Y'))
plt.xticks(rotation = -90)
plt.tight_layout()
plt.show()

结果:


这是丑陋的。我希望标记与数据框中的位置完全相同,但线条要平滑。我知道 scipy -> spline (例如 here ),但是转换所有列似乎太麻烦了。还有 Pandas -> resample -> interpolate (例如 here )这非常接近我想要的但我必须将 Date 列转为 我不想做的索引...

如果您能帮助我了解执行此操作的最佳 Pythonic 方式是什么,我将不胜感激。


P.S.完整版我的代码可以看here .

最佳答案

我认为你需要编写一个遍历所有的自定义绘图函数 列和绘图将数据插值到指定的轴实例。看下面的代码:

import pandas as pd
import numpy as np

# data = pd.read_clipboard()
# data.drop(['Index'], axis=1, inplace=True)

def add_smooth_plots(df, ax,  timecolumn='Date', interpolation_method='cubic', colors='rgbky'):
    from itertools import cycle
    ind = pd.to_datetime(df.loc[:, timecolumn])
    tick_labels =ind.dt.strftime("%Y-%m-%d")
    color = cycle(colors)
    for i, col in enumerate(df.columns):
        if col != timecolumn:
            c = next(color)
            s = pd.Series(df.loc[:, col].values, index=ind)
            intp = s.resample('0.5D').interpolate(method=interpolation_method)
            true_ticks = intp.index.isin(ind)
            vals = intp.values
            intp = intp.reset_index()
            ticks = intp.index[true_ticks]
            ax.plot(np.arange(len(vals)), vals, label=col, color=c)
            ax.set_xticks(ticks)
            ax.set_xticklabels(tick_labels.values, rotation=45)
            ax.legend(title='Columns')
    return ax

from matplotlib import pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)

add_smooth_plots(data, ax)

plt.show()

enter image description here

关于python - 平滑绘制数据框的所有列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55736800/

相关文章:

python - 为什么我无法按预期显示错误消息?

python - 在 SQLAlchemy 中按空值过滤 postgres JSON 列

python - Python 实现中的 Sha-3

Python pandas DataFrame 列和传递的数据似乎大小不同,但没有

python - 3D 图显示错误的轴标签(X 轴有 Y 轴名称,Y 轴有 X 轴名称)

r - 在 R 中的轴标题中同时使用下标和变量值

python - 如何使 QListWidget 项目可编辑

python - 使用pandas获取按天的数据累计和

python - 使用固定宽度的列保存数据框

r - ggplot中中位数置信区间的计算