【问题标题】:Pandas Bar Plot using Subplots使用子图的 Pandas 条形图
【发布时间】:2018-06-14 18:13:54
【问题描述】:

我正在使用 pandas 来创建条形图。这是一个例子:

df=pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
df.plot(kind='bar')

我想在一个图中绘制两个子图,并在一个条形图上有 a 和 b,在另一个条形图上有 c 和 d。我该怎么办?

此外,如果我想将两个子图包含在另一个子图中但不是由 pandas 创建的,该怎么做?所以一个 3x1 的图,其中两个子图来自使用 pandas 的数据框,一个不使用 pandas。

对此进行第二次尝试,但进行了一些修改。

df=pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
x=[1,2,3,4,5]
y=[1,4,9,16,25]

fig, axes = plt.subplots(figsize=(8,8),nrows=2, ncols=2)
ax1=plt.subplot(2,2,1)
plt.plot(x,y)

#ax2=plt.subplot(2,2,2)
df["b"].plot(ax=axes[0,1], kind='bar', grid=True)
df["c"].plot(ax=axes[1,0], kind='bar', grid=True)
df["d"].plot(ax=axes[1,1], kind='bar', grid=True)

ax1.grid(True)
ax1.set_ylabel('Test')
ax1.set_xlabel('Test2')

#ax2.set_ylabel('Test')

如何在我的子图中为条形图添加轴标签?请注意,我在测试时已注释掉 ax2=plt.subplot(2,2,2) ,但这会完全擦除条形图并添加标签。为什么它会这样做,我该如何解决这个问题?下面是带有 ax2... 未注释的输出。

【问题讨论】:

  • 嗨。标题具有误导性。看看documentations
  • 我已经看过这个,但并没有真正帮助我。

标签: pandas plot


【解决方案1】:

你可以从这里开始玩:

%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.DataFrame(np.random.rand(10, 4),
                  columns=['a', 'b', 'c', 'd'])

fig, axes = plt.subplots(nrows=1, ncols=2)
df[["a","b"]].plot(ax=axes[0], kind='bar')
df[["c", "d"]].plot(ax=axes[1], kind='bar');

那你可以看看this

【讨论】:

  • 这很有帮助——非常感谢。我有一个关于条形图标签的后续问题。
  • @CharanjitPabla 如果我的回答有用,请点赞并最终接受。作为 SO 政策,您应该分别提出不同的问题。这样做,其他有相同问题的人很容易找到参考资料。
  • 仅供参考,当nrows > 1ncols > 1 然后axesn * m 数组。见here
猜你喜欢
  • 2021-08-03
  • 2020-02-09
  • 2018-11-28
  • 1970-01-01
  • 2021-12-27
  • 2020-10-20
  • 2019-12-23
  • 2020-04-06
  • 1970-01-01
相关资源
最近更新 更多