You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用matplotlib的plt.axhline()绘制最优拟合线的技术咨询

Adding an Optimal Fit Line to Your Matplotlib Plot

Hey there! Let's break down how to add that red fit line you've hand-drawn. First, let's clarify two common scenarios since you mentioned plt.axhline()—it's built for horizontal lines, but if your desired line is a sloped regression fit, we'll need a slightly different approach.

Scenario 1: Horizontal Fit Line (e.g., Mean of Your y-values)

If you want a horizontal line (like the average of your mutation appearance values), plt.axhline() is exactly what you need. Here's how to use it effectively:

Key Parameters for plt.axhline():

  • y: Required — The y-axis value where the horizontal line will sit (e.g., the mean of your y dataset)
  • c/color: Line color (use 'r' for red to match your hand-drawn line)
  • linewidth/lw: Thickness of the line to make it stand out
  • linestyle/ls: Style of the line (e.g., '--' for dashed, '-' for solid)
  • xmin/xmax: Optional — Control the line's start/end as a fraction of the x-axis (0 = left edge, 1 = right edge; default is 0 to 1)

Full Code Example:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame(pd.read_csv('test5.csv', sep=','))
x = df["IE ratio"]
y = df["109"]

x1 = df["IE ratio"].mean()
plt.axvline(x1, 0, 1, c='k')  # Your existing vertical midline

# Calculate the mean of y-values and draw the horizontal fit line
y_mean = y.mean()
plt.axhline(y=y_mean, c='r', linewidth=2, linestyle='--', label='Mean Mutation Appearance')

plt.scatter(x, y, s=10)
plt.ylabel('Appearance of mutation')
plt.xlabel('IE spectrum')
plt.legend()
plt.show()

Scenario 2: Sloped Linear Regression Fit Line

If your hand-drawn red line is a sloped optimal fit (linear regression) through your scatter points, plt.axhline() won't work—we need to calculate the regression first using numpy.polyfit().

Full Code Example:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

df = pd.DataFrame(pd.read_csv('test5.csv', sep=','))
x = df["IE ratio"]
y = df["109"]

x1 = df["IE ratio"].mean()
plt.axvline(x1, 0, 1, c='k')  # Your existing vertical midline

# Calculate linear regression coefficients (slope m, intercept b)
m, b = np.polyfit(x, y, 1)
# Generate y-values for the fit line
y_fit = m * x + b
# Plot the sloped optimal fit line
plt.plot(x, y_fit, c='r', linewidth=2, label='Optimal Linear Fit')

plt.scatter(x, y, s=10)
plt.ylabel('Appearance of mutation')
plt.xlabel('IE spectrum')
plt.legend()
plt.show()

This will draw a red line that best fits your scatter data, matching the hand-drawn effect you described.

内容的提问来源于stack exchange,提问作者RJCoder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 13:02:36