将 matplotlib 绘图轴设置为数据框列名称 [英] Set matplotlib plot axis to be the dataframe column name
问题描述
我有一个像这样的数据框:
I have a dataframe like so:
data = DataFrame({'Sbet': [1,2,3,4,5], 'Length' : [2,4,6,8,10])
然后我有一个函数来绘制和拟合这些数据
Then I have a function that plots and fits this data
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)
然后我将在数据框上调用该函数:
Then I would call the function on the dataframe:
linregress(data['Sbet'],data['Length'])
我的问题是如何在函数中将x轴标签和y轴标签设为 Sbet
和 Length
,并将图标题设为Sbet vs Length
我已经尝试了一些东西,但是当我使用 plt.xlabel(data['Sbet'])
和 plt 时,我倾向于恢复整列.title
.
My question is how do I get the x axis label and y axis label to be Sbet
and Length
within the function as well as the plot title to be Sbet vs Length
I've tried a few things but I tend to get the whole column back when I use plt.xlabel(data['Sbet'])
and plt.title
.
推荐答案
有序列
使用定义顺序的列构建数据框:
Ordered columns
Build your dataframe with the columns in a defined order:
data = DataFrame.from_items([('Sbet', [1,2,3,4,5]), ('Length', [2,4,6,8,10])])
现在您可以将第一列用作 x
,将第二列用作 y
:
Now you can use the first column as x
and the second column as 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)
明确的列名
字典没有有用的顺序.因此,您不知道列顺序,而需要显式提供名称顺序.
Explicit column names
Dictionaries have not useful order. Therefore, you don't know the column order and you need to supply the order of names explicitly.
这将起作用:
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')
这篇关于将 matplotlib 绘图轴设置为数据框列名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!