【问题标题】:Matplotlib - Extending linear regression line to entire width of graph [duplicate]Matplotlib - 将线性回归线扩展到图形的整个宽度[重复]
【发布时间】:2019-01-31 21:09:00
【问题描述】:

我似乎无法弄清楚如何让线性回归线(又名最佳拟合线)跨越图形的整个宽度。它似乎只是沿着左边最远的数据点和右边最远的数据点上升,没有进一步。我该如何解决这个问题?

import matplotlib.pyplot as plt
import numpy as np
from scipy import stats
from scipy.interpolate import *
import MySQLdb

# connect to MySQL database
def mysql_select_all():
    conn = MySQLdb.connect(host='localhost',
                           user='root',
                           passwd='XXXXX',
                           db='world')
    cursor = conn.cursor()
    sql = """
        SELECT
            GNP, Population
        FROM
            country
        WHERE
            Name LIKE 'United States'
                OR Name LIKE 'Canada'
                OR Name LIKE 'United Kingdom'
                OR Name LIKE 'Russia'
                OR Name LIKE 'Germany'
                OR Name LIKE 'Poland'
                OR Name LIKE 'Italy'
                OR Name LIKE 'China'
                OR Name LIKE 'India'
                OR Name LIKE 'Japan'
                OR Name LIKE 'Brazil';
    """

    cursor.execute(sql)
    result = cursor.fetchall()

    list_x = []
    list_y = []

    for row in result:
        list_x.append(('%r' % (row[0],)))

    for row in result:
        list_y.append(('%r' % (row[1],)))

    list_x = list(map(float, list_x))
    list_y = list(map(float, list_y))

    fig = plt.figure()
    ax1 = plt.subplot2grid((1,1), (0,0))

    p1 = np.polyfit(list_x, list_y, 1)          # this line refers to line of regression

    ax1.xaxis.labelpad = 50
    ax1.yaxis.labelpad = 50

    plt.plot(list_x, np.polyval(p1,list_x),'r-') # this refers to line of regression  
    plt.scatter(list_x, list_y, color = 'darkgreen', s = 100)
    plt.xlabel("GNP (US dollars)", fontsize=30)
    plt.ylabel("Population(in billions)", fontsize=30)
    plt.xticks([1000000, 2000000, 3000000, 4000000, 5000000, 6000000, 
                7000000, 8000000, 9000000],  rotation=45, fontsize=14)
    plt.yticks(fontsize=14)

    plt.show()
    cursor.close()

mysql_select_all()

【问题讨论】:

  • x的较大和较小值处评估您的多项式?
  • 我该怎么做?
  • plt.plot([little_x, big_x], np.polyval(p1, [little_x, big_x]),'r-')
  • little_x, big_x... 是那些任意数字还是你说的是 min x value max x value?
  • 它们是您希望线条包含的任何跨度。

标签: python matplotlib


【解决方案1】:

MySQLdb 未安装在我的系统上,因此我无法运行您的代码,但以下代码行肯定可以工作。

EDIT 基于 cmets:您还必须设置 x-limits

x_low = 0.9*min(list_x)
x_high = 1.1*max(list_x)
x_extended = np.linspace(x_low, x_high, 100)

p1 = np.polyfit(list_x, list_y, 1)             # this line refers to line of regression

ax1.xaxis.labelpad = 50
ax1.yaxis.labelpad = 50

plt.plot(x_extended, np.polyval(p1,x_extended),'r-')   # this line refers to line of regression
plt.xlim(x_low, h_high)

【讨论】:

  • 它仍然显示相同的东西
  • @NickT: 试试x_extended = np.linspace(500000, 10000000, 100) 让我知道
  • 我试过了。它只是改变了轴标签
  • @NickT:你数据中的最小和最大 x 值是多少?
  • 尝试添加 plt.xlim(15000, 10510700) 并检查您是否看到了什么。可能是轴没有延伸。不幸的是,我无法运行您的代码
【解决方案2】:

由于您没有包含数据,因此这里是一个使用一些人工数据的简单示例。 这里的想法是找出回归线的值在绘图的 x 限制处,然后强制 matplotlib 不要在数据边缘添加正常的“缓冲区”。

import numpy as np
import matplotlib.pyplot as plt

x = [1, 1.8, 3.3, 3.5, 5.5, 6.1]
y = [1, 2.1, 3.0, 3.7, 5.2, 6.4]

p1 = np.polyfit(x, y, 1)

plt.scatter(x, y)
xlims = plt.xlim()
x.insert(0, xlims[0])
y.insert(0, np.polyval(p1, xlims[0]))
x.append(xlims[1])
y.append(np.polyval(p1, xlims[1]))
plt.plot(x, np.polyval(p1,x), 'r-', linewidth = 1.5)
plt.xlim(xlims)
plt.show()

在不扩展回归线的情况下,样本数据看起来像

而在扩展之后,

【讨论】:

    【解决方案3】:

    如果您希望绘图不超出 x 轴上的数据,只需执行以下操作:

    fig, ax = plt.subplots()
    ax.margins(x=0)
    # Don't use plt.plot
    ax.plot(list_x, np.polyval(p1,list_x),'r-')
    ax.scatter(list_x, list_y, color = 'darkgreen', s = 100)
    ax.set_xlabel("GNP (US dollars)", fontsize=30)
    ax.set_ylabel("Population(in billions)", fontsize=30)
    ax.set_xticks([1000000, 2000000, 3000000, 4000000, 5000000, 6000000, 7000000, 8000000, 9000000],  rotation=45, fontsize=14)
    ax.tick_params(axis='y', labelsize=14)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-17
      • 2018-02-01
      • 1970-01-01
      • 2011-03-29
      • 1970-01-01
      • 2017-01-18
      • 2018-04-21
      • 1970-01-01
      相关资源
      最近更新 更多