【问题标题】:Create subplots from various tables using matplotlib使用 matplotlib 从各种表创建子图
【发布时间】:2019-09-24 13:19:12
【问题描述】:

我有 6 个 2011-2016 年基于犯罪的数据集。我提取了一个名为“Priority”的列,其值只能为 1 或 2。这基本上是说犯罪的优先级为 1 或 2。我从每个数据集中创建了一个单独的表,以便计算每个数据集中的优先级。

    Priority  Count in 2011
1       1.0          36699
2       2.0         143314

   Priority  Count in 2012
0       1.0          41926
1       2.0         145504

   Priority  Count in 2013
1       1.0          43171
2       2.0         144859

   Priority  Count in 2014
0         1          42773
1         2         144707

   Priority  Count in 2015
1         1          42418
2         2         150162

   Priority  Count in 2016
0       1.0          24555
1       2.0          86272

我希望生成一个 3x2 subplot,这是一个条形图类型。我知道怎么做,但是当我尝试将所有 6 个一起制作时,出现了错误。

我一直在谷歌上搜索如何做到这一点,并遇到了 matplotlib 网站 (https://matplotlib.org/3.1.1/gallery/subplots_axes_and_figures/subplots_demo.html),它引导我找到了一段我适应的代码:

fig, axs = plt.subplots(3, 2)
plt.set_title('2011 Priority Counts')
axs[0, 0].pri_2011.plot.bar()
axs[0, 0].xlabel('Priority Type')
axs[0, 0].ylabel('Reported crimes')

    .
    .
    .

plt.set_title('2016 Priority Counts')
axs[3, 2].pri_2016.plot.bar()
axs[3, 2].xlabel('Priority Type')
axs[3, 2].ylabel('Reported crimes')
plt.show()

这会产生许多错误,例如: "AttributeError: module 'matplotlib.pyplot' has no attribute 'set_title'", "AttributeError: 'AxesSubplot' object has no attribute 'pri_2011'", 等等

我曾考虑在命令中包含“pri_2011”,使其成为位于左侧子图位置 [0, 0] 的第一个图形,这将来自第一个表。 'pri_2016' 将位于子图的右下角,是要显示的最后一个图。

谁能指导我正确的做法?

【问题讨论】:

  • 您可以这样做,而无需将它们分成不同的表。
  • 但它们最初是从不同的数据集上传的?
  • 查看我的更新答案

标签: python pandas matplotlib


【解决方案1】:

你可以这样做:

axes = plt.subplots(3,2)
list_df = [df1,df2,...]

for df, ax in zip(list_df, axes):
    df.plot.bar(x='Priority', ax=ax)
    ax.label(...)
    ...

您可以这样做,而无需将它们分成不同的表。例如:

df = pd.DataFrame([
    [1, 36699, 41926,43171,42773,42418,24555],
    [2, 143314, 145504, 144859, 144707, 150162, 86272]
],
columns=['Priority']+[f'Count in {x}' for x in range(2011,2017)]
)

df.plot.bar(x='Priority', subplots=True, layout=(3,2));

给予:

【讨论】:

  • 这行得通 - 谢谢!我将如何增加地块的大小,以免它们被挤在一起?
  • axes = plt.subplots(3,2, figsize=(12,9)) 根据您的需要更改 figsize
猜你喜欢
  • 2017-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-21
  • 1970-01-01
  • 1970-01-01
  • 2017-09-07
相关资源
最近更新 更多