【问题标题】:Python Create Bar Chart Comparing 2 sets of dataPython创建条形图比较2组数据
【发布时间】:2019-04-10 11:15:13
【问题描述】:

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

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

显示如下图:

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

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

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

我试过了,这只是我在试验:

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

任何建议将不胜感激!

【问题讨论】:

  • 您好,听起来您需要一个分组条形图。请发布一些示例数据,以便人们进行实验。另外,贴出你需要使用的Python包——matplotlibpandas等。如果你可以将夏季和冬季数据结合在一起,那么matplotlib(12)或@就有这样的例子987654324@ 绘图。如果它们必须分开存放,请参阅1

标签: python pandas bar-chart


【解决方案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()

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

您可以在此处查看 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)

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

【讨论】:

    【解决方案2】:

    创建一个包含 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-19
      • 2023-03-26
      • 2021-01-10
      • 2016-07-06
      • 2018-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多