【问题标题】:Set matplotlib plot axis to be the dataframe column name将 matplotlib 绘图轴设置为数据框列名
【发布时间】:2016-04-11 17:33:49
【问题描述】:

我有一个这样的数据框:

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 时,往往会恢复整个专栏。

【问题讨论】:

    标签: python numpy pandas matplotlib


    【解决方案1】:

    有序列

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

    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?
    猜你喜欢
    • 2020-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-23
    • 1970-01-01
    • 1970-01-01
    • 2022-11-18
    • 2020-11-23
    相关资源
    最近更新 更多