Python 将matplotlib plot axis设置为数据框列名

Python 将matplotlib plot axis设置为数据框列名,python,numpy,pandas,matplotlib,Python,Numpy,Pandas,Matplotlib,我有这样一个数据帧: data = DataFrame({'Sbet': [1,2,3,4,5], 'Length' : [2,4,6,8,10]) 然后我有一个函数来绘制和拟合这些数据 def lingregress(x,y): slope, intercept, r_value, p_value, std_err = stats.linregress(x,y) r_sq = r_value ** 2 plt.scatter(x,y) plt.plot(x,

我有这样一个数据帧:

data = DataFrame({'Sbet': [1,2,3,4,5], 'Length' : [2,4,6,8,10])
然后我有一个函数来绘制和拟合这些数据

def lingregress(x,y):
    slope, intercept, r_value, p_value, std_err = stats.linregress(x,y)
    r_sq = r_value ** 2

    plt.scatter(x,y)
    plt.plot(x,intercept + slope * x,c='r')

    print 'The slope is %.2f with R squared of %.2f' % (slope, r_sq)
然后我将调用数据帧上的函数:

 linregress(data['Sbet'],data['Length'])
我的问题是如何在函数中使x轴标签和y轴标签成为
Sbet
Length
,以及使绘图标题成为
Sbet vs Length
我尝试了一些方法,但在使用
plt.xlabel(data['Sbet')时,我倾向于使整个列返回
plt.title

有序列 按定义的顺序使用列构建数据框架:

data = DataFrame.from_items([('Sbet', [1,2,3,4,5]), ('Length', [2,4,6,8,10])])
现在,您可以使用第一列作为
x
,第二列作为
y

def lingregress(data):
    x_name = data.columns[0]
    y_name = data.columns[1]
    x = data[x_name]
    y = data[y_name]
    slope, intercept, r_value, p_value, std_err = stats.linregress(x,y)
    r_sq = r_value ** 2

    plt.scatter(x,y)
    plt.xlabel(x_name)
    plt.ylabel(y_name)
    plt.title('{x_name} vs. {y_name}'.format(x_name=x_name, y_name=y_name))
    plt.plot(x,intercept + slope * x,c='r')

    print('The slope is %.2f with R squared of %.2f' % (slope, r_sq))


lingregress(data)
显式列名 字典没有有用的顺序。因此,您不知道列的顺序,需要显式地提供名称的顺序

这将有助于:

def lingregress(data, x_name, y_name):
    x = data[x_name]
    y = data[y_name]
    slope, intercept, r_value, p_value, std_err = stats.linregress(x,y)
    r_sq = r_value ** 2

    plt.scatter(x,y)
    plt.xlabel(x_name)
    plt.ylabel(y_name)
    plt.title('{x_name} vs. {y_name}'.format(x_name=x_name, y_name=y_name))
    plt.plot(x,intercept + slope * x,c='r')

    print('The slope is %.2f with R squared of %.2f' % (slope, r_sq))


lingregress(data, 'Sbet', 'Length')

这是大量的手工/显式工作。想象一下,有许多列名称。。真的没有更智能/自动的推理方式将df中的一列名称链接到matplotlib了吗?