将matplotlib绘图轴设置为dataframe列名

时间:2016-01-07 10:50:48

标签: 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,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轴标签设为SbetLength,并将图标标题设为Sbet vs Length我是尝试了一些事情,但是当我使用plt.xlabel(data['Sbet'])plt.title时,我倾向于让整个专栏回来。

1 个答案:

答案 0 :(得分:3)

有序列

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

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')

enter image description here