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

Sympy implicit_plot x轴固定显示在y=0的调整需求

解决Sympy隐函数图迁移到Matplotlib后x轴定位问题

你的问题出在move_sympyplot_to_axes函数里的脊柱定位设置:原代码中ax.spines['bottom'].set_position('zero')会强制x轴固定在y=0的位置,即便你限制了y轴显示范围为[20,60],x轴的基准仍未改变。要实现x轴与y轴在y=20处交汇,只需修改脊柱的定位规则,同时调整相关轴的显示设置。

以下是修改后的完整代码:

import numpy as np
import matplotlib.pyplot as plt
from sympy import plot_implicit, symbols

def get_rotation_matrix(deg):
    rad = np.deg2rad(deg)
    return np.array([[np.cos(rad), -np.sin(rad)],
                    [np.sin(rad), np.cos(rad)]])

def move_sympyplot_to_axes(p, ax, y_axis_intersection=20):
    backend = p.backend(p)
    backend.ax = ax
    backend._process_series(backend.parent._series, ax, backend.parent)
    
    # 隐藏不需要的脊柱
    ax.spines['right'].set_visible(False)
    ax.spines['top'].set_visible(False)
    
    # 设置x轴(底部脊柱)定位到y=y_axis_intersection处
    ax.spines['bottom'].set_position(('data', y_axis_intersection))
    # 设置y轴(左侧脊柱)定位到x轴的最小值处,确保与x轴交汇
    ax.spines['left'].set_position(('data', ax.get_xlim()[0]))
    
    # 调整轴标签位置
    ax.set_xlabel(ax.get_xlabel(), ha='right', x=1, labelpad=0)
    ax.set_ylabel(ax.get_ylabel(), ha='right', va='top', y=1, labelpad=0, rotation=0)
    
    # 确保y轴刻度从设定的交汇值开始
    ax.set_yticks(np.arange(y_axis_intersection, ax.get_ylim()[1]+1, 10))
    
    plt.close(backend.fig)

a = 20
b = 10
u = get_rotation_matrix(60)
center= np.array((35, 35))

x, y = symbols('x y')

# 椭圆函数
f = ((x-center[0])/a)**2 + ((y-center[1])/b)**2 - 1

# 绘制隐函数图
p = plot_implicit(f, (x, -20, 60), (y, 20, 60), aspect_ratio=(1,1), 
                  axis_center=center.tolist(), xlabel="x", ylabel="y", 
                  title="", show=False)

f, ax = plt.subplots()
# 传入y轴交汇位置20
move_sympyplot_to_axes(p, ax, y_axis_intersection=20)
plt.show()

关键修改说明:

  • 脊柱定位调整:
    • 将ax.spines['bottom'].set_position('zero')替换为ax.spines['bottom'].set_position(('data', 20)),直接指定x轴沿y=20的位置绘制。
    • 添加ax.spines['left'].set_position(('data', ax.get_xlim()[0])),让y轴固定在x轴的最小值处,确保两者在左下角(最小x值,20)交汇,和Matplotlib的默认轴交汇逻辑一致。
  • 刻度优化:
    • 添加ax.set_yticks(np.arange(y_axis_intersection, ax.get_ylim()[1]+1, 10)),让y轴刻度从20开始,避免显示20以下的无效刻度。
  • 函数参数化:
    • 给move_sympyplot_to_axes添加y_axis_intersection参数,方便后续修改交汇位置,提升代码复用性。

这样修改后,x轴会准确显示在y=20的位置,和y轴完成交汇,同时保留你需要的隐函数图+Matplotlib拓展能力(后续可以直接在ax上添加散点等元素)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 09:05:55