Python创建比较两个数据集的条形图 [英] Python Create Bar Chart Comparing 2 sets of data
问题描述
我有一个带2 *条形图的笔记本,一个是冬季数据&一是夏季数据.我已经计算了所有犯罪的总数,并使用代码将其绘制在条形图中:
I have a notebook with 2* bar charts, one is winter data & one is summer data. I have counted the total of all the crimes and plotted them in a bar chart, using code:
ax = summer["crime_type"].value_counts().plot(kind='bar')
plt.show()
其中显示的图形如下:
我有另一张几乎相同的图表,但是是冬天的:
I have another chart nearly identical, but for winter:
ax = winter["crime_type"].value_counts().plot(kind='bar')
plt.show()
我想在同一条形图中将这两个图表相互比较(x轴上的每个犯罪都有2个条形,一个冬天,一个夏天).
And I would like to have these 2 charts compared against one another in the same bar chart (Where every crime on the x axis has 2 bars coming from it, one winter & one summer).
我已经尝试过,这只是我的尝试:
I have tried, which is just me experimenting:
bx = (summer["crime_type"],winter["crime_type"]).value_counts().plot(kind='bar')
plt.show()
任何建议将不胜感激!
Any advice would be appreciated!
推荐答案
以下内容将生成您的数据的虚拟变量,并执行您想要的分组条形图:
The following generates dummies of your data and does the grouped bar chart you wanted:
import random
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
s = "Crime Type Summer|Crime Type Winter".split("|")
# Generate dummy data into a dataframe
j = {x: [random.choice(["ASB", "Violence", "Theft", "Public Order", "Drugs"]
) for j in range(300)] for x in s}
df = pd.DataFrame(j)
index = np.arange(5)
bar_width = 0.35
fig, ax = plt.subplots()
summer = ax.bar(index, df["Crime Type Summer"].value_counts(), bar_width,
label="Summer")
winter = ax.bar(index+bar_width, df["Crime Type Winter"].value_counts(),
bar_width, label="Winter")
ax.set_xlabel('Category')
ax.set_ylabel('Incidence')
ax.set_title('Crime incidence by season, type')
ax.set_xticks(index + bar_width / 2)
ax.set_xticklabels(["ASB", "Violence", "Theft", "Public Order", "Drugs"])
ax.legend()
plt.show()
有了这个脚本,我得到了:
With this script I got:
您可以在此处查看matplotlib文档中的演示: https://matplotlib.org /gallery/statistics/barchart_demo.html
You can check out the demo in the matplotlib docs here: https://matplotlib.org/gallery/statistics/barchart_demo.html
要注意的重要事项是索引!
The important thing to note is the index!
index = np.arange(5) # Set an index of n crime types
...
summer = ax.bar(index, ...)
winter = ax.bar(index+bar_width, ...)
...
ax.set_xticks(index + bar_width / 2)
这些是将条形图排列在水平轴上的线,以便将它们分组在一起.
These are the lines that arrange the bars on the horizontal axis so that they are grouped together.
这篇关于Python创建比较两个数据集的条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!