gpt4 book ai didi

python - 我如何在 matplotlib 中获得笛卡尔坐标系?

转载 作者:太空狗 更新时间:2023-10-29 17:17:20 32 4
gpt4 key购买 nike

我是 Python 绘图新手,无法真正找到问题的答案:How can I get Cartesian coordinate plane in matplotlib?我的意思是垂直引用线(坐标轴)以箭头结尾,在原点 (0,0) 处相交,原点位于绘图的中心。

想一想做高中几何的飞机,以下是我需要实现的完美示例:

Plot with Cartesian coordiantes

最佳答案

这是另一种绘制笛卡尔坐标系的方法,它建立在已经给出的答案之上。

import numpy as np                 # v 1.19.2
import matplotlib.pyplot as plt # v 3.3.2

# Enter x and y coordinates of points and colors
xs = [0, 2, -3, -1.5]
ys = [0, 3, 1, -2.5]
colors = ['m', 'g', 'r', 'b']

# Select length of axes and the space between tick labels
xmin, xmax, ymin, ymax = -5, 5, -5, 5
ticks_frequency = 1

# Plot points
fig, ax = plt.subplots(figsize=(10, 10))
ax.scatter(xs, ys, c=colors)

# Draw lines connecting points to axes
for x, y, c in zip(xs, ys, colors):
ax.plot([x, x], [0, y], c=c, ls='--', lw=1.5, alpha=0.5)
ax.plot([0, x], [y, y], c=c, ls='--', lw=1.5, alpha=0.5)

# Set identical scales for both axes
ax.set(xlim=(xmin-1, xmax+1), ylim=(ymin-1, ymax+1), aspect='equal')

# Set bottom and left spines as x and y axes of coordinate system
ax.spines['bottom'].set_position('zero')
ax.spines['left'].set_position('zero')

# Remove top and right spines
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)

# Create 'x' and 'y' labels placed at the end of the axes
ax.set_xlabel('x', size=14, labelpad=-24, x=1.03)
ax.set_ylabel('y', size=14, labelpad=-21, y=1.02, rotation=0)

# Create custom major ticks to determine position of tick labels
x_ticks = np.arange(xmin, xmax+1, ticks_frequency)
y_ticks = np.arange(ymin, ymax+1, ticks_frequency)
ax.set_xticks(x_ticks[x_ticks != 0])
ax.set_yticks(y_ticks[y_ticks != 0])

# Create minor ticks placed at each integer to enable drawing of minor grid
# lines: note that this has no effect in this example with ticks_frequency=1
ax.set_xticks(np.arange(xmin, xmax+1), minor=True)
ax.set_yticks(np.arange(ymin, ymax+1), minor=True)

# Draw major and minor grid lines
ax.grid(which='both', color='grey', linewidth=1, linestyle='-', alpha=0.2)

# Draw arrows
arrow_fmt = dict(markersize=4, color='black', clip_on=False)
ax.plot((1), (0), marker='>', transform=ax.get_yaxis_transform(), **arrow_fmt)
ax.plot((0), (1), marker='^', transform=ax.get_xaxis_transform(), **arrow_fmt)

plt.show()

Cartesian coordinate system

请注意,根据我的经验,我没有添加显示点坐标的注释,它需要更多代码才能很好地定位它们并尽量减少重叠。要获得注释,最好使用 adjustText package或交互式图形库,例如 Plotly .

关于python - 我如何在 matplotlib 中获得笛卡尔坐标系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13430231/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com