【问题标题】:Python. Multiple plots via for loops, fixing axisPython。通过 for 循环绘制多个图,固定轴
【发布时间】:2022-12-05 22:26:10
【问题描述】:

我是 python 的新手。我必须在不同的时间迭代绘制一些数据。该图是一个 3d 散点图。该图有一些我想修复的错误:查看三个不同时间实例(第一个、中间和最后一个)的图

first

middle

last

  • 如您所见,每个图像周围都有一个框,被标题“图表标题”截断了。我想删除这条框线(我不明白它来自哪里)。注意我想保留轴标题。
  • 在中间和最后一张图片中,坐标轴上的数字似乎重叠,我只想为每张图片固定三个轴中的每一个。

如何编辑我的代码来执行上述操作。

fig, ax = plt.subplots()

for n in range(10):
    #labels
    ax=plt.axes(projection='3d') 
    ax.set_title('graph title')
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_zlabel('z')
    ax.set_xlim(left=-10, right=20)
    ax.set_ylim(bottom=-10, top=20)
    ax.set_zlim(bottom=-10, top=20)

    #plotting
    x=data[n]
    ax.scatter(x[:,0],x[:,1],x[:,2])
    plt.savefig(f'fig_{n}.png')
    plt.cla() # needed to remove the plot because savefig doesn't clear it

【问题讨论】:

    标签: python matplotlib axis subplot axis-labels


    【解决方案1】:

    主要问题是您没有注意到您在同一个图形上创建了多个轴。

    您首先使用 fig, ax = plt.subplots() 创建一个,然后在 for 循环中使用 ax=plt.axes(projection='3d') 创建其他的。 这就是盒子的来源,它是下面绘制的轴的盒子。 这也是为什么您在坐标轴上有重叠刻度的原因。

    此外,如果您只创建一次ax,则无需在 for 循环中设置其标题、标签等:

    import matplotlib.pyplot as plt
    import numpy as np
    
    T = 4  # time
    N = 34  # samples
    D = 3  # x, y, z
    
    data = np.random.rand(T, N, D)
    
    fig, ax = plt.subplots(subplot_kw=dict(projection="3d"))
    ax.set_title("graph title")
    ax.set_xlabel("x")
    ax.set_ylabel("y")
    ax.set_zlabel("z")
    ax.set_xlim(left=0, right=1)
    ax.set_ylim(bottom=0, top=1)
    ax.set_zlim(bottom=0, top=1)
    
    
    colors = iter(["blue", "green", "red", "yellow", "pink"])
    for n, points in enumerate(data):
        x, y, z = points.T
        scat = ax.scatter(x, y, z, c=next(colors))
        fig.savefig(f'fig_{n}.png')
        scat.remove()  # ax.cla() clears too much (title etc.)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-19
      • 2014-12-08
      • 1970-01-01
      • 1970-01-01
      • 2021-05-25
      • 1970-01-01
      • 2021-02-09
      • 1970-01-01
      相关资源
      最近更新 更多