我有一个像这样的数据框:
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')
关于python - 将 matplotlib 绘图轴设置为数据框列名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34653259/