如何移除顶部和右侧坐标轴?

230 投票
10 回答
215830 浏览
提问于 2025-04-15 11:54

我想要的不是默认的“框状”坐标轴样式,而是只保留左边和底部的坐标轴,也就是说:

+------+         |
|      |         |
|      |   --->  |
|      |         |
+------+         +-------

这应该很简单,但我在文档里找不到需要的选项。

10 个回答

33

[编辑] 现在(2013年10月)matplotlib的版本是1.3.0,里面包含了这个功能。

这个功能其实是最近才添加的,你需要使用Subversion版本才能使用它。你可以在这里看到示例代码。

我只是想更新一下,告诉大家现在网上有一个更好的示例。不过还是需要Subversion版本,目前还没有发布包含这个功能的正式版本。

[编辑] Matplotlib 0.99.0 RC1刚刚发布,里面包含了这个功能。

74

另外,这段代码

def simpleaxis(ax):
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.get_xaxis().tick_bottom()
    ax.get_yaxis().tick_left()

似乎可以在不失去旋转标签支持的情况下,实现相同的效果。

(适用于Matplotlib 1.0.1;这个解决方案的灵感来自于这个链接。)

287

这是来自官方网站的推荐解决方案,适用于Matplotlib 3,详细内容可以在这里找到:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)

ax = plt.subplot(111)
ax.plot(x, y)

# Hide the right and top spines
ax.spines[['right', 'top']].set_visible(False)

plt.show()

在这里输入图片描述

撰写回答