Python创建条形图比较2组数据

时间:2018-11-07 01:20:24

标签: python pandas bar-chart

我有一个带2 *条形图的笔记本,一个是冬季数据,一个是夏季数据。我已经计算了所有犯罪的总数,并使用代码将其绘制在条形图中:

ax = summer["crime_type"].value_counts().plot(kind='bar')
plt.show()

显示的图形如下:

enter image description here

我有另一张几乎相同的图表,但是是冬天的:

ax = winter["crime_type"].value_counts().plot(kind='bar')
plt.show()

我想在同一条形图中将这两个图表相互比较(x轴上的每个犯罪都有2个条形,一个冬天一个夏天)。

我已经尝试过,这只是我的尝试:

bx = (summer["crime_type"],winter["crime_type"]).value_counts().plot(kind='bar')
plt.show()

任何建议将不胜感激!

2 个答案:

答案 0 :(得分:1)

以下内容将生成您的数据的虚拟变量,并执行您想要的分组条形图:

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

有了这个脚本,我得到了:

this image

您可以在以下网址查看matplotlib文档中的演示:https://matplotlib.org/gallery/statistics/barchart_demo.html

要注意的重要事项是索引!

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)

这些是将条形图排列在水平轴上的线,以便将它们分组在一起。

答案 1 :(得分:0)

创建一个包含犯罪类型、计数、季节 3 列的 Pandas 数据框,然后试试这个功能。

#Importing required packages

import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import MaxNLocator

#Function Creation
def plt_grouped_bar(Plot_Nm,group_bar,x, y,plt_data,**bar_kwargs):
    plt_fig=plt.figure(figsize=(18,9))
    ax=plt_fig.add_subplot()
    g = sns.catplot(x=x, y=y, hue=group_bar,data=plt_data,ax=ax,kind="bar",**bar_kwargs)
    for p in ax.patches:
        height = p.get_height()
        ax.text(x = p.get_x()+(p.get_width()/2),
        y = height+0.05,
        s = '{:.0f}'.format(height),
        ha = 'center',va = 'bottom',zorder=20, rotation=90)
    ax.set_title(Plot_Nm,fontweight="bold",fontsize=18,alpha=0.7,y=1.03)
    g.set_xticklabels(x,fontsize=10,alpha=0.8,fontweight="bold")
    plt.setp(ax.get_xticklabels(), rotation=90)
    ax.set_yticklabels("")
    ax.set_xlabel("")
    ax.set_ylabel("")
    ax.yaxis.set_major_locator(MaxNLocator(integer=True))
    ax.tick_params(axis=u'both',length=0)
    ax.legend(loc='upper right')
    for spine in ax.spines:
        ax.spines[spine].set_visible(False)
    plt.close()

#Calling the function
plt_grouped_bar('Title of bar','weather','crimetype','count',pandasdataframename)