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

Python使用Matplotlib绘制二次函数时如何标注x轴交点及对应坐标

二次方程求解可视化代码(需求实现版)

修改说明

  • 实现曲线与x轴交点的红色圆点标记
  • 实现交点下方的坐标值显示(保留2位小数)
  • 原有英文交互提示全部翻译为中文
  • 增加解去重逻辑,重根不会重复绘制标记

若方程解超出当前x轴[-6,6]显示范围,可自行调整x = np.linspace(-6, 6, 50)和plt.xlim([-6, 6])的上下限参数即可正常显示

完整代码

import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import numpy as np
import math


def int_input(prompt):
    while True:
        try:
            variable_name = int(input(prompt))
            return variable_name
        except ValueError:
            print("请输入整数(阿拉伯数字)")


def float_input(prompt):
    while True:
        try:
            variable_name = float(input(prompt))
            return variable_name
        except ValueError:
            print("请输入数字(阿拉伯数字)")


def yes_input(prompt):
    while True:
        variable_name = input(prompt).lower()
        if variable_name in ["y", "yes"]:
            return "yes"
        elif variable_name in ["n", "no"]:
            return "no"
        else:
            print("请输入「y」或「n」")


print("=== 二次方程求解器 ===")

while True:
    print("请输入形如ax² + bx + c = 0的方程参数")
    a = float_input('a的值:')
    b = float_input('b的值:')
    c = float_input('c的值:')

    # 计算判别式
    d = (b ** 2) - (4 * a * c)

    # 求解
    try:
        solution1 = (-b - math.sqrt(d)) / (2 * a)
    except ValueError:
        solution1 = "none"

    try:
        solution2 = (-b + math.sqrt(d)) / (2 * a)
    except ValueError:
        solution2 = "none"

    if solution1 == solution2:
        if solution1 == "none":
            print("该方程无实根")
        else:
            print(f"该方程有1个实根:x = {solution1}")
    else:
        print(f"该方程有2个实根:x = {solution1} 或 x = {solution2}")

    graph = yes_input("是否要绘制函数图像?(y/n):")
    if graph == "yes":
        x = np.linspace(-6, 6, 50)
        fig = plt.figure(figsize=(7, 4))
        y4 = a * x ** 2 + b * x + c
        plt.plot(x, y4, 'g:', label='二次函数')

        # 新增:绘制交点标记和坐标
        solutions = set()
        if solution1 != "none":
            solutions.add(solution1)
        if solution2 != "none":
            solutions.add(solution2)
        for x_sol in solutions:
            # 绘制红色圆点标记,zorder确保圆点在曲线上层
            plt.scatter(x_sol, 0, c='red', s=60, zorder=10, label='实根' if '实根' not in [text.get_text() for text in plt.gca().get_legend_handles_labels()[1]] else "")
            # 在交点下方显示坐标,ha='center'确保文本水平居中
            plt.text(x_sol, -0.3, f'({x_sol:.2f}, 0)', ha='center', c='darkred', fontsize=9)

        # 图像属性设置
        plt.legend()
        plt.grid(True, linestyle=':')
        plt.xlim([-6, 6])
        plt.ylim([-4, 4])
        plt.title(f'二次函数 {a}x² + {b}x + {c} 的图像')
        plt.xlabel('x轴')
        plt.ylabel('y轴')
        plt.get_current_fig_manager().window.wm_geometry("+0+0")
        fig.canvas.manager.window.attributes('-topmost', 1)
        plt.show()

    new_question = yes_input('是否要计算新的方程?(y/n):')
    if new_question == "no":
        break

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 06:45:04