如何在python中平滑图形中的线条?

如何在python中平滑图形中的线条?,python,pandas,matplotlib,plot,lines,Python,Pandas,Matplotlib,Plot,Lines,用下面的代码,我可以画一个有三条线的图形,但它们是有角度的。有可能把这些线弄平吗 import matplotlib.pyplot as plt import pandas as pd # Dataframe consist of 3 columns df['year'] = ['2005, 2005, 2005, 2015, 2015, 2015, 2030, 2030, 2030'] df['name'] = ['A', 'B', 'C', 'A', 'B', 'C', 'A', 'B',

用下面的代码,我可以画一个有三条线的图形,但它们是有角度的。有可能把这些线弄平吗

import matplotlib.pyplot as plt
import pandas as pd

# Dataframe consist of 3 columns
df['year'] = ['2005, 2005, 2005, 2015, 2015, 2015, 2030, 2030, 2030']
df['name'] = ['A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C']
df['weight'] = [80, 65, 88, 65, 60, 70, 60, 55, 65]
fig,ax = plt.subplots()

# plot figure to see how the weight develops through the years
for name in ['A','B','C']:
    ax.plot(df[df.name==name].year,df[df.name==name].weight,label=name)

ax.set_xlabel("year")
ax.set_ylabel("weight")
ax.legend(loc='best')

你应该对你的数据应用插值,它不应该是“线性的”。在这里,我使用scipy的
interp1d
应用了“立方”插值。另外,请注意,使用三次插值时,数据应至少有4个点。所以我又加了一个2031年和另一个值,也就是所有权重(我从权重的最后一个值中减去1得到了新的权重值):

代码如下:

import matplotlib.pyplot as plt
import pandas as pd
from scipy.interpolate import interp1d
import numpy as np

# df['year'] = ['2005, 2005, 2005, 2015, 2015, 2015, 2030, 2030, 2030']
# df['name'] = ['A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C']
# df['weight'] = [80, 65, 88, 65, 60, 70, 60, 55, 65]

df1 = pd.DataFrame()
df1['Weight_A'] = [80, 65,  60 ,59]
df1['Weight_B'] = [65, 60,  55 ,54]
df1['Weight_C'] = [88, 70,  65 ,64]
df1.index = [2005,2015,2030,2031]


ax = df1.plot.line()
ax.set_title('Before interpolation')
ax.set_xlabel("year")
ax.set_ylabel("weight")

f1 = interp1d(df1.index, df1['Weight_A'],kind='cubic')
f2 = interp1d(df1.index, df1['Weight_B'],kind='cubic')
f3 = interp1d(df1.index, df1['Weight_C'],kind='cubic')

df2 = pd.DataFrame()
new_index = np.arange(2005,2031)
df2['Weight_A'] = f1(new_index)
df2['Weight_B'] = f2(new_index)
df2['Weight_C'] = f3(new_index)
df2.index = new_index

ax2 = df2.plot.line()
ax2.set_title('After interpolation')
ax2.set_xlabel("year")
ax2.set_ylabel("weight")


plt.show()
结果是:


@poke我认为这不是同一个问题。我以前试过另一个问题的答案。我只是不知道为什么它不起作用,但我认为它有点不同,因为你必须在这里使用3列或数组,而不是其他只有2个数组的问题。你必须在绘制数据之前插入数据,SOwoow中的大量示例非常感谢!!我几乎花了一整天的时间试图消除这些障碍,但还是放弃了。最后,我只是在每个数据之间加上一个点,使其平滑一点。你的代码对我帮助很大,谢谢@朱莉:没问题:)