Python 使用matplotlib从各种表创建子图
我有6组2011-2016年的犯罪数据。我提取了一个名为“Priority”的列,它的值只能是1或2。这基本上是说,一项犯罪属于优先权1或2。为了计算每个数据集中的优先级,我从每个数据集中创建了一个单独的表Python 使用matplotlib从各种表创建子图,python,pandas,matplotlib,Python,Pandas,Matplotlib,我有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
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
网站(),该网站引导我走向一段代码,我将其改编为:
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));
给出:
您可以这样做,而无需将它们分成不同的表。但它们最初是从不同的数据集上载的?请参阅我的最新答案,该答案有效-谢谢!如何增加绘图的大小,使其不被挤压在一起?
axes=plt.子绘图(3,2,figsize=(12,9))
根据需要更改figsize
。