[Python][matplotlib.pyplot] Move the X and Y coordinate axes to the origin (0,0), so that the scale numbers are spaced at 1, and the actual distance between the scales of the X and Y axes (how many pixels) is the same, and the grid is added Grid

question:

Python uses matplotlib.pyplot to draw lines, the coordinate axes are on the leftmost and bottommost, and the scale numbers of the coordinate axes are not at intervals of 1, and the scale spacing (pixels) of the X-axis and Y-axis are also different. How to solve it? Please read below.

code:

# -*- coding: utf-8 -*-
"""
Created on Mon Jul 24 11:01:24 2023

@author: howard
"""
import numpy as np
import matplotlib.pyplot as plt


#调整坐标轴:坐标轴移到原点(0,0);坐标轴刻度数字间隔1;刻度之间的像素一样
def adjustAxis():
    # 创建图形和坐标轴对象
    fig, ax = plt.subplots()
    
    # 设置Y轴在0位置
    ax.spines['left'].set_position('zero')
    # 设置X轴在0位置
    ax.spines['bottom'].set_position('zero')
    
    # 隐藏右边和上边的坐标轴线
    ax.spines['right'].set_color('none')
    ax.spines['top'].set_color('none')
    
    # 设置X、Y轴刻度间隔为1
    ax.xaxis.set_major_locator(plt.MultipleLocator(1))
    ax.yaxis.set_major_locator(plt.MultipleLocator(1))
    
    # 调整图形的大小,保持宽高大小一样,才能保证X轴和Y轴刻度之间的像素间隔相等
    fig.set_size_inches(5, 5)  # 根据需要调整图形的大小
    
    #这个步骤是画网格线
    plt.grid(True, linestyle="--", alpha=0.5)


# 利用 matplotlib 来进行画图
def drawXY():
    
    adjustAxis()
    
    # param:起点,终点,间距
    x = np.arange(-3,4,1)
    y = x
    plt.plot(x, y)

    plt.show()
 
 
if __name__ == '__main__':
    drawXY()

Actual renderings

 Of course, there is a small problem:

Since this graph will automatically adapt to the size of the window, when the value ranges of X and Y are different, or after changing the size of the window with the mouse, the pixels between the scales of the X and Y axes cannot be kept the same.

Guess you like

Origin blog.csdn.net/H_O_W_E/article/details/131892191