使用 pandas 的绘图方法在1行中绘制图形的问题 [英] Problem with plotting graphs in 1 row using plot method from pandas

查看:62
本文介绍了使用 pandas 的绘图方法在1行中绘制图形的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想在1行中绘制3个图形:其他3个要素的依存关系cnt.

Suppose I want to plot 3 graphs in 1 row: dependencies cnt from other 3 features.

代码:

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)尺寸时,一切正常:

But everything is ok when I'm plotting in (2,2) dimension:

代码:

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]在多行的情况下有效.

The problem is not related to pandas. The index error you see comes from ax= axes[0, idx]. This is because you have a single row. [0, idx] would work when you have more than one row.

仅一行,您可以跳过第一个索引并使用

For just one row, you can skip the first index and use

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])

这篇关于使用 pandas 的绘图方法在1行中绘制图形的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆