在 matplotlib 中设置 X 和 Y 限制会导致输出出现行错误

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

我正在尝试绘制一个圆,并且希望背景看起来像一张方格纸,但是当我尝试设置 X 和 Y 限制时,线条变得混乱。我的圈子代码是:

R1 = (n1 + n2 + n3) / 2

circle1 = (0, 0, R1)
circle2 = (0, R1, R1)
circle3 = (0, 2 * R1, 2 * R1)
circle4 = (0, 4 * R1, 2 * R1)

x2 = circle2[0] + circle2[2] * np.cos(theta)
y2 = circle2[1] + circle2[2] * np.sin(theta)
plt.plot(x2, y2, label='Circle 2')

x3 = circle3[0] + circle3[2] * np.cos(theta)
y3 = circle3[1] + circle3[2] * np.sin(theta)
plt.plot(x3, y3, label='Circle 3')

我设置了 X 和 Y 限制以匹配绘图纸的限制。不过,使 X 和 Y 限制动态化可以解决这个问题。下面是我的 X 和 Y 限制的代码:

plt.figure(figsize=(6.8, 8.6), dpi=100)
theta = np.linspace(0, 2 * np.pi, 100)
ax = plt.gca()



# Set the limits for x and y axes
ax.set_xlim(-17.5, 17.5)
ax.set_ylim(0, 50)

但是我在图中得到的结果看起来是这样的: 输出

python numpy matplotlib
1个回答
0
投票

您可能需要更改 n1/n2/n3 的值才能获得圆,并更改网格间距,但这里有一个示例,其中您使用自定义图形限制来生成网格 + 刻度。 基本上,它会根据您设置的最小/最大值为您的轴生成间隔为 1 和 0.5 的刻度线和线条。

import numpy as np
import matplotlib.pyplot as plt

n1 = 2
n2 = 3
n3 = 4

plt.figure(figsize=(6.8, 8.6), dpi=100)
theta = np.linspace(0, 2 * np.pi, 100)

R1 = (n1 + n2 + n3) / 2

circle1 = (0, 0, R1)
circle2 = (0, R1, R1)
circle3 = (0, 2 * R1, 2 * R1)
circle4 = (0, 4 * R1, 2 * R1)

x2 = circle2[0] + circle2[2] * np.cos(theta)
y2 = circle2[1] + circle2[2] * np.sin(theta)
plt.plot(x2, y2, label='Circle 2')

x3 = circle3[0] + circle3[2] * np.cos(theta)
y3 = circle3[1] + circle3[2] * np.sin(theta)
plt.plot(x3, y3, label='Circle 3')

# Set the limits for x and y axes + grid
ax = plt.gca()

x_min = -17
x_max = 17
ax.set_xlim(x_min, x_max)
x_ticks = np.arange(x_min, x_max, 1)
little_x_ticks = np.arange(x_min, x_max, 0.5)
ax.set_xticks(x_ticks)
ax.set_xticks(little_x_ticks, minor=True)

y_min = 0
y_max = 50
ax.set_ylim(y_min, y_max)
y_ticks = np.arange(y_min, y_max, 1)
little_y_ticks = np.arange(y_min, y_max, 0.5)
ax.set_yticks(y_ticks)
ax.set_yticks(little_y_ticks, minor=True)

plt.grid(which='both', axis='both')

结果是这样的: Img

© www.soinside.com 2019 - 2024. All rights reserved.