Python Pandas/Matplotlib-从多个数据框列平滑线图

Python Pandas/Matplotlib-从多个数据框列平滑线图,python,pandas,dataframe,matplotlib,Python,Pandas,Dataframe,Matplotlib,我想用数据帧中的虚拟数据平滑出一个简单的线图。我知道插值,但所有教程都使用更简单的numpy数组;我希望由列生成的每一行都是平滑的。如果任何人有经验,或知道如何做到这一点,将不胜感激 以下是一些代码和结果图,供参考 # amps df=pd.read_csv("~/data/poli.csv") ################################# # wp wave = (df.right + df.left)**2 df['concord'] = wave print(

我想用数据帧中的虚拟数据平滑出一个简单的线图。我知道插值,但所有教程都使用更简单的numpy数组;我希望由列生成的每一行都是平滑的。如果任何人有经验,或知道如何做到这一点,将不胜感激

以下是一些代码和结果图,供参考

# amps

df=pd.read_csv("~/data/poli.csv")

#################################

# wp

wave = (df.right + df.left)**2
df['concord'] = wave
print(df)
哪些产出:

         issue  right  left  concord
0      end div      1     1        4
1    for trump      1    -1        0
2  aisle cross      1     1        4
3      for blm     -1     1        0
4   help world      1     1        4
5      service      1     1        4
6    community      1     1        4
然后我绘制列,将x轴设置为“问题”,将y标签设置为“分数”

plot = df.plot(x='issue',
             linewidth=9,
             alpha=0.36)

plot.set_ylabel('score')
plot.set_xlabel('issues')
plot.legend(bbox_to_anchor=(1, 1), loc='upper left', ncol=1)

concord=df['concord'].values
left=df['left'].values
right=df['right'].values

plt.show()
并生成结果图


正如您所说,您需要对曲线进行插值以提高分辨率。这样,您可以在保持数据的已知值的同时仍然有效地平滑曲线。为此,可以使用scipy的一维插值:

我们希望插值到比我们拥有的更多的x坐标,但这里的问题是,作为
,和
协和
“函数”的自变量,你有字符串而不是数字。为了解决这个问题,我们可以简单地将您的
问题
列映射到一个单调递增的数值向量,然后使用从中获取的极限值插入一个新向量,最后将x标签保留为字符串。
更新后的代码可以是:

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

d = {
     'issue': ['end div', 'for trump', 'aisle cross', 'for blm', 'help world',
     'service', 'community'],
     'right': [1, 1, 1, -1, 1, 1, 1],
     'left': [1, -1, 1, 1, 1, 1, 1],
     'concord': [4, 0, 4, 0, 4, 4, 4]
     }
df = pd.DataFrame.from_dict(d)

x = df['issue'].values
concord = df['concord'].values
left = df['left'].values
right = df['right'].values

n = len(x)
x_map = np.arange(0,n)
dx = 0.1
x_int = np.arange(0, n - 1, dx)  # vector where we interpolate

# We create the interpolants our three datasets separately:
f_concord = interpolate.interp1d(x_map, concord, 'quadratic')
f_left = interpolate.interp1d(x_map, left, 'quadratic')
f_right = interpolate.interp1d(x_map, right, 'quadratic')

# And interpolate in the resampled x-coordinates:
concord_int = f_concord(x_int)
left_int = f_left(x_int)
right_int = f_right(x_int)

# Finally, plot the interpolated data:
fig, ax = plt.subplots()
ax.plot(x_int, right_int, lw = 9, alpha = 0.36, label = 'right')
ax.plot(x_int, left_int, lw = 9, alpha = 0.36, label = 'left')
ax.plot(x_int, concord_int, lw = 9, alpha = 0.36, label = 'concord')
ax.set_xlabel('issues')
ax.set_ylabel('score')
# Set the correct xticks
ax.set_xticks(x_map)
ax.set_xticklabels(x)
fig.legend(bbox_to_anchor=(0.7, 0.3), loc='upper left', ncol=1)
fig.show()
结果是:

平滑每条曲线本质上需要在中间x值处生成额外的数据点。这些点与您当前拥有的任何一个类别都不对应。因此,您必须首先平滑每一列(样条线应该做什么?),根据线性增加的x轴绘制它们(例如,0到30,取决于平滑产生的点数),最后手动调整刻度,以便每个极值对应于第一列中的一个条目。