python-3.x - 在子图中绘制不同的数据帧数据

标签 python-3.x pandas dataframe matplotlib data-visualization

我正在尝试在两个子图中的两个数据框中绘制数据。我指的是this link

import pandas as pd
import numpy as np
from pprint import pprint
from matplotlib import pyplot as plt


df1 = pd.DataFrame(np.random.randn(10, 10))
df2 = pd.DataFrame(np.random.randn(10, 10))


plt.figure()
fig, axes = plt.subplots(nrows=1, ncols=2)

df1.plot(ax=axes[0, 0], style='o-')
axes[0, 0].set_xlabel('x')
axes[0, 0].set_ylabel('y')
axes[0, 0].set_title('ttl')

df2.plot(ax=axes[0, 1], style='o-')
axes[0, 1].set_xlabel('x')
axes[0, 1].set_ylabel('y')
axes[0, 1].set_title('ttl')

但是,我收到以下错误

df1.plot(ax=axes[0, 0], style='o-')
IndexError: too many indices for array

任何有关如何解决此问题的建议都会非常有帮助。 编辑:下面提供的答案适用于 1 行 2 列

我遇到 2 行 2 列错误

import pandas as pd
import numpy as np
from pprint import pprint
from matplotlib import pyplot as plt


df1 = pd.DataFrame(np.random.randn(10, 10))
df2 = pd.DataFrame(np.random.randn(10, 10))
df3 = pd.DataFrame(np.random.randn(10, 10))
df4 = pd.DataFrame(np.random.randn(10, 10))

pprint(df1)

plt.figure()
fig, axes = plt.subplots(nrows=2, ncols=2)

df1.plot(ax=axes[0], style='o-')
axes[0].set_xlabel('x')
axes[0].set_ylabel('y')
axes[0].set_title('ttl')

df2.plot(ax=axes[1], style='o-')
axes[1].set_xlabel('x')
axes[1].set_ylabel('y')
axes[1].set_title('ttl')


df3.plot(ax=axes[2], style='o-')
axes[2].set_xlabel('x')
axes[2].set_ylabel('y')
axes[2].set_title('ttl')

df4.plot(ax=axes[3], style='o-')
axes[3].set_xlabel('x')
axes[3].set_ylabel('y')
axes[3].set_title('ttl')

plt.show()

错误:

AttributeError: 'numpy.ndarray' object has no attribute 'get_figure'

有什么建议吗?

最佳答案

轴是一维的,你必须这样做:

df1.plot(ax=axes[0], style='o-')
df2.plot(ax=axes[1], style='o-')

我建议阅读this ,看看squeeze参数你就会明白这是怎么回事。

关于python-3.x - 在子图中绘制不同的数据帧数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61042878/

相关文章:

python - tensorflow 中大型稀疏矩阵的特征向量

python - pandas 列名分配中的大写优先

python - 从列中的文本中提取国家/地区名称以创建另一列

python - 使用分层索引更新数据框

python - 为什么我的生成器没有返回任何值?

python - 如何解析 Python3 BeautifulSoup 中的 onclick() 文本?

python-3.x - 无法在 M1 Mac 上使用 Pip 安装 OpenCV

python - 在 pandas 中旋转数据

pandas - 选择多次分组后时间上的最后一个值

python - Pandas 新列作为另一列的字符串提取,仅在验证字符串长度的特定条件下 : Fast way