gpt4 book ai didi

python - 使用 matplotlib 从各种表创建子图

转载 作者:行者123 更新时间:2023-12-01 07:13:52 25 4
gpt4 key购买 nike

我有 6 个 2011-2016 年基于犯罪的数据集。我提取了一个名为“优先级”的列,该列的值只能为 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 子图,它是条形图类型。我知道如何做一个,但是当我尝试同时生成所有 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:模块'matplotlib.pyplot'没有属性'set_title'”“AttributeError:'AxesSubplot'对象没有属性'pri_2011'”,等等

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

有人可以指导我正确的方法吗?

最佳答案

你可以这样做:

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

给出:

enter image description here

关于python - 使用 matplotlib 从各种表创建子图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58081254/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com