python - 使用 pandas 的绘图方法在 1 行中绘制图形的问题
问题描述
假设我想在 1 行中绘制 3 个图:cnt
来自其他 3 个特性的依赖关系。
代码:
fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(15, 10))
for idx, feature in enumerate(min_regressors):
df_shuffled.plot(feature, "cnt", subplots=True, kind="scatter", ax= axes[0, idx])
plt.show()
错误信息:
IndexErrorTraceback (most recent call last)
<ipython-input-697-e15bcbeccfad> in <module>()
2 fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(15, 10))
3 for idx, feature in enumerate(min_regressors):
----> 4 df_shuffled.plot(feature, "cnt", subplots=True, kind="scatter", ax= axes[0, idx])
5 plt.show()
IndexError: too many indices for array
但是当我在 (2,2) 维度上绘图时一切正常:
代码:
fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(15, 10))
for idx, feature in enumerate(min_regressors):
df_shuffled.plot(feature, "cnt", subplots=True, kind="scatter", ax= axes[idx / 2, idx % 2])
plt.show()
输出:
我在用着python 2.7
解决方案
该问题与熊猫无关。您看到的索引错误来自ax= axes[0, idx]
. 这是因为您只有一行。[0, idx]
当你有不止一排时会起作用。
对于一行,您可以跳过第一个索引并使用
fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(15, 10))
for idx, feature in enumerate(min_regressors):
df_shuffled.plot(feature, "cnt", subplots=True, kind="scatter", ax= axes[idx])
plt.show()
作为回顾
正确的
fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(8, 3))
axes[0].plot([1,2], [1,2])
不正确
fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(8, 3))
axes[0, 0].plot([1,2], [1,2])
正确的
fig, axes = plt.subplots(nrows=2, ncols=3, figsize=(8, 3))
axes[0,0].plot([1,2], [1,2])
推荐阅读
- c# - 如何高效生成List
基于自定义模式? - node.js - 节点找不到绑定文件
- javascript - 如何让赛普拉斯包含返回布尔值而不是测试失败
- office-js - 清单中的语言覆盖不起作用
- angular - 当我在 Android 模拟器上运行构建时,Ionic App 在登录后崩溃
- macos - Mac vscode:使用 ctrl + 鼠标单击的多行
- javascript - 如何在firebase中从一个集合访问另一个集合
- jmeter - 当 jmeter 等待先前的响应发送新请求时,如何在 jmeter 中表示现实世界?
- python - 如何在 python 中模拟 Firestore where 函数?
- ios - iOS 设备 Flutter 上的 Flutter image_picker 问题