在类中制作x轴,y轴

问题描述 投票:0回答:1

我使用 python 来制作图表。我用箭头制作了 x 轴、y 轴,并删除了不使用轴的情况。但它太长了,所以我一次又一次地使用这个代码时遇到问题。

import matplotlib.pyplot as plt

fig = plt.figure()
ax=fig.add_subplot()

x_max, y_max = 1, 1 ## coordinate of arrow

## x축 화살표

x_arrow_width = 0.01 ## 화살 폭

x_arrow = Polygon( \[\[x_max-np.sqrt(3)\*x_arrow_width, -x_arrow_width\],
\[x_max-np.sqrt(3)\*x_arrow_width, x_arrow_width\],
\[x_max, 0\]\], ## 삼각형 경로
closed=True, ## 닫힌 경로로 설정
fill=True, ## 색상 채움
color='k', ## 색상
transform=ax.transAxes, ## 표시될 좌표체계 설정 left-bottom (0,0) \~ right-top (1,1)
clip_on=False ## 맨앞으로 보내기
)
ax.add_patch(x_arrow) # 삼각형 추가

## y - axis

y_arrow_width = x_arrow_width
y_arrow = Polygon( \[\[-y_arrow_width, y_max-np.sqrt(3)\*y_arrow_width\],
\[y_arrow_width, y_max-np.sqrt(3)\*y_arrow_width\],
\[0, y_max\]\], ## triangle path
closed=True, ## set it to the closed path
fill=True, ## fill color
color='k', ## color
transform=ax.transAxes,
clip_on=False ## sent to the front)
ax.add_patch(y_arrow) #add triangle

## remove not using axes

ax.spines\['right'\].set_visible(False)
ax.spines\['top'\].set_visible(False)

我想在课堂上编写这段代码。是否可以?我怎样才能做到?

python matplotlib graph axis
1个回答
0
投票

尝试这样

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon

class ArrowAxes:
    def __init__(self, x_max=1, y_max=1, arrow_width=0.01):
        self.fig = plt.figure()
        self.ax = self.fig.add_subplot()
        self.x_max = x_max
        self.y_max = y_max
        self.arrow_width = arrow_width

    def create_x_axis(self):
        x_arrow = Polygon([
            [self.x_max - np.sqrt(3) * self.arrow_width, -self.arrow_width],
            [self.x_max - np.sqrt(3) * self.arrow_width, self.arrow_width],
            [self.x_max, 0]
        ],
        closed=True,
        fill=True,
        color='k',
        transform=self.ax.transAxes,
        clip_on=False)
        self.ax.add_patch(x_arrow)

    def create_y_axis(self):
        y_arrow = Polygon([
            [-self.arrow_width, self.y_max - np.sqrt(3) * self.arrow_width],
            [self.arrow_width, self.y_max - np.sqrt(3) * self.arrow_width],
            [0, self.y_max]
        ],
        closed=True,
        fill=True,
        color='k',
        transform=self.ax.transAxes,
        clip_on=False)
        self.ax.add_patch(y_arrow)

    def remove_unused_axes(self):
        self.ax.spines['right'].set_visible(False)
        self.ax.spines['top'].set_visible(False)

    def show(self):
        plt.show()

# Example usage:
if __name__ == "__main__":
    arrow_axes = ArrowAxes()
    arrow_axes.create_x_axis()
    arrow_axes.create_y_axis()
    arrow_axes.remove_unused_axes()
    arrow_axes.show()
© www.soinside.com 2019 - 2024. All rights reserved.