首页 > 解决方案 > 如何在 matlibplot 中自定义坐标轴

问题描述

我有两点p1=(0.86, 0.5) & p2=(0.86, -0.5)想使用 matlibplot 绘制它们所以我尝试了以下方法:

import matplotlib.pyplot as plt
p1=[0.86, 0.5] 
p2=[0.86, -0.5]
plt.scatter(p1[0], p1[1])
plt.scatter(p2[0], p2[1])

我得到以下结果:

在此处输入图像描述

但是,我想要的是根据坐标系在 p1 和 p2 之间进行旋转,使其看起来如下所示:

在此处输入图像描述

那么如何像上图那样调整坐标系呢?

标签: pythonmatplotlibplotrotation

解决方案


这并不完全是您所追求的,但应该让您了解如何实现所需的显示。重要的位是设置脊椎属性和刻度线的位置。您可以在轴上添加刻度以“压缩”视图比例以匹配您的示例。我还提供了一个显示箭头的方法示例。

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

import matplotlib.pyplot as plt

p1=[0.86, 0.5] 
p2=[0.86, -0.5]

# Create figure and subplot
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

# Plot data points
ax.scatter(p1[0], p1[1], color='blue')
ax.scatter(p2[0], p2[1], color='orange')

# Set limits for x and y axes
plt.xlim(-1, 1)
plt.ylim(-1, 1)

# ===== Important bits start here =====

# Set properties of spines
ax.spines['top'].set_color('none')
ax.spines['left'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position('zero')

# Set axis tick positions
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

# Set specific tick locations
ax.set_xticks([-1, -0.5, 0, 0.5, 1])
ax.set_yticks([-1, -0.5, 0.5, 1])

# ===== End Of Important Bits =====

# Draw arrows
ax.arrow(0, 0 , p1[0], p1[1], 
    head_width=0.03, 
    head_length=0.1, 
    lw=1, 
    fc='blue', 
    ec='blue', 
    length_includes_head=True)
    
ax.arrow(0, 0 , p2[0], p2[1], 
    head_width=0.03, 
    head_length=0.1, 
    lw=1, 
    fc='orange', 
    ec='orange', 
    length_includes_head=True)

plt.show()

样本输出

示例输出图


推荐阅读