【问题标题】:Inverting axis of matplotlib 3D plot ruins ticksmatplotlib 3D绘图废墟的倒轴刻度
【发布时间】:2019-06-19 11:44:14
【问题描述】:

我将使用官方的 Matplotlib 3.1.0 example code 来绘制 3D 散点图:

# This import registers the 3D projection, but is otherwise unused.
from mpl_toolkits.mplot3d import Axes3D  # noqa: F401 unused import

import matplotlib.pyplot as plt
import numpy as np

# Fixing random state for reproducibility
np.random.seed(19680801)


def randrange(n, vmin, vmax):
    '''
    Helper function to make an array of random numbers having shape (n, )
    with each number distributed Uniform(vmin, vmax).
    '''
    return (vmax - vmin)*np.random.rand(n) + vmin

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

n = 100

# For each set of style and range settings, plot n random points in the box
# defined by x in [23, 32], y in [0, 100], z in [zlow, zhigh].
for m, zlow, zhigh in [('o', -50, -25), ('^', -30, -5)]:
    xs = randrange(n, 23, 32)
    ys = randrange(n, 0, 100)
    zs = randrange(n, zlow, zhigh)
    ax.scatter(xs, ys, zs, marker=m)

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()

它绘制以下图像:

现在我想颠倒 Y 轴的绘图顺序。我尝试在填充情节的 for 循环之后添加 ax.invert_yaxis(),但它什么都不做。在ax = fig.add_subplot(111, projection='3d') 之后添加该行确实会反转绘图本身,但它会弄乱沿 y 轴的刻度:

我做错了还是可能是一个错误? (我知道我可以以倒排数组的形式传递数据,但我觉得这样的解决方案会不太干净)。

【问题讨论】:

  • 添加ax.invert_yaxis() 在外部和之后 for 循环对我来说很好,并且颠倒了 y 轴刻度的顺序。在散点中,您几乎没有注意到差异,但查看刻度值以查看差异
  • @Sheldore 有意思,你用的是 3.1.0 版吗?
  • 不,我还在使用 2.2.2。 ;) 在您的情况下,3+ 似乎有些问题

标签: python matplotlib plot


【解决方案1】:

在 Matplotlib 3.5.0 中不再出现带有损坏刻度的错误,而是存在另一个错误,导致 ax.invert_yaxis() 在限制 y 轴的同时实际反转 x 轴:

在此报告:https://github.com/matplotlib/matplotlib/issues/21369

有一种解决方法实际上会反转 y 轴。而不是ax.invert_yaxis(),使用

ylim = ax.get_ylim()
ax.set_yticks(ax.get_yticks())
ax.set_ylim(ylim[::-1])

虽然此代码冻结了 y 刻度,但它确实成功地正确反转了 y 轴,因此在许多应用程序中都应该这样做。只需在反转 y 轴之前设置轴限制和刻度位置,这不会打扰您。

【讨论】:

    猜你喜欢
    • 2012-01-21
    • 1970-01-01
    • 2012-05-08
    • 2014-07-31
    • 2016-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-02
    相关资源
    最近更新 更多