python - 将 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,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.

最佳答案

有序列

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

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

关于python - 将 matplotlib 绘图轴设置为数据框列名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34653259/

相关文章:

使用 newaxis 对 for 循环进行 Python 时间优化

python - Pandas 使用 tldextract 加入单元格中的最后 2 个逗号分隔项

python - Python 中的滚动平均成对相关性

python - 在 OS-X Lion 上安装 Graphite。如何配置apache2?

python - 50% 处的 CDF x 值和平均值不显示相同的数字

python - 如何按第二级对多索引数据帧进行排序

pandas - 如何提取 Pandas 中的年、月和日?

javascript - Django 1.10 - 使用 django.shortcuts.render 生成带有变量的网页,其中包含 javascript 作为参数

python - 需要平均 Python 的帮助

python - 估计卡尔曼滤波器周围的置信区间