【问题标题】:I'm having trouble plotting a 2D graph alongside a 3D graph using mat plot lib我在使用 mat plot lib 绘制 2D 图和 3D 图时遇到问题
【发布时间】:2022-01-24 17:25:49
【问题描述】:

我有一个生成 3d 图形的代码块

ax = plt.axes(projection = '3d')
ax.plot3D(outputs_real, outputs_imaginary, inputs)
ax.set_xlabel('Real Component')
ax.set_ylabel('Imaginary Component')
ax.set_zlabel('Inputs')
plt.show()

以及第二个代码块,它使用上述轴中的 2 个制作二维图。

ax2 = plt.plot(outputs_real, outputs_imaginary)
ax2.set_xlabel('Real Component')
ax2.set_ylabel('Imaginary Component')

但由于某种原因,当我尝试绘制第二个时,我会收到此错误

AttributeError: 'list' object has no attribute 'set_xlabel'

第二个图会像这样映射到第一个图上:

我希望两个图表分开

详情:

  1. 这是在 Jupyter 笔记本中完成的
  2. outputs_real、outputs_imaginary 和 inputs 都是列表

【问题讨论】:

标签: python matplotlib


【解决方案1】:

从 matplotlib documentation plt.plot 返回代表绘制数据的线条列表。

如果要更改 x 和 y 标签,请使用 plt.xlabel('text')plt.ylabel('text'),如下所示:

plt.plot(outputs_real, outputs_imaginary)
plt.xlabel('Real Component')
plt.ylabel('Imaginary Component')

创建 2D 和 3D 单独图表的示例:

import numpy as np
from matplotlib import pyplot as plt

# create 3d data
z = np.linspace(0, 15, 1000)
x = np.sin(z)
y = np.cos(z)

# plot 3D
fig = plt.figure(figsize=(10,5))
ax = fig.add_subplot(111, projection='3d')
ax.plot3D(x, y, z)
ax.set_title("3D plot")
ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.set_zlabel("Z")
plt.show()

# plot 2D
plt.plot(x, y)
plt.title("2D plot")
plt.xlabel("X")
plt.ylabel("Y")
plt.show()

这将创建以下两个图:

【讨论】:

    【解决方案2】:

    一种选择是创建一个新图形。在你调用了第一个 plt.show() 之后,创建一个新的图形和斧头

    plt.figure(2)
    ax2 = plt.axes()
    

    如果需要,您还可以同时绘制两个图形,方法是在创建两个图形后不调用第一个 plt.show() 并仅调用 plt.show()

    【讨论】:

      猜你喜欢
      • 2018-10-26
      • 1970-01-01
      • 1970-01-01
      • 2013-09-06
      • 1970-01-01
      • 1970-01-01
      • 2021-12-03
      • 1970-01-01
      • 2021-11-09
      相关资源
      最近更新 更多