我的数据框为:
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
列更改为index
,我不想这样做...
如果您能帮助我了解执行此操作的最佳Pythonic方法,将不胜感激。
PS 。我的代码的完整版本可以在here上看到。
答案 0 :(得分:1)
我认为您需要编写一个自定义绘制函数,该函数可对所有对象进行迭代 列并绘制插值数据到指定的轴实例。看下面的代码:
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()