【问题标题】:How do I plot a Bar graph when comparing the rows? [duplicate]比较行时如何绘制条形图? [复制]
【发布时间】:2024-01-18 18:22:01
【问题描述】:

我无法在此数据集上绘制条形图。

+------+------------+--------+
| Year | Discipline | Takers |
+------+------------+--------+
| 2010 | BSCS       |   213  |
| 2010 | BSIS       |   612  |
| 2010 | BSIT       |   796  |
| 2011 | BSCS       |   567  |
| 2011 | BSIS       |   768  |
| 2011 | BSIT       |   504  |
| 2012 | BSCS       |   549  |
| 2012 | BSIS       |   595  |
| 2012 | BSIT       |   586  |
+------+------------+--------+

我正在尝试绘制一个条形图,其中 3 个条形表示每年的接受者数量。这是我做的算法。

import matplotlib.pyplot as plt
import pandas as pd

Y = df_group['Takers']
Z = df_group['Year']

df = pd.DataFrame(df_group['Takers'], index = df_group['Discipline'])
df.plot.bar(figsize=(20,10)).legend(["2010", "2011","2012"])

plt.show()

我希望展示类似这张图的东西

有着相同的传说

【问题讨论】:

    标签: python python-3.x pandas matplotlib jupyter-notebook


    【解决方案1】:

    只需在代码中的 plt.show() 之前再添加 2 行,您就会得到结果。 整个代码如下。

    import matplotlib.pyplot as plt
    import pandas as pd
    
    Y = df_group['Takers']
    Z = df_group['Year']
    
    df = pd.DataFrame(df_group['Takers'], index = df_group['Discipline'])
    df.plot.bar(figsize=(20,10)).legend(["2010", "2011","2012"])
    
    for i,v in enumerate(Y):
        plt.text(x=i, y=v+2, s=v)
        # Here i= index value  
        # v= real value which you have in variable Y.
        # x and y are coordinate.
        # 's' is the value you want to show on the plot.
    
    plt.show()
    

    【讨论】:

      【解决方案2】:

      使用Seaborn,您可以直接使用您的Dataframe:

      import seaborn as sns
      ax = sns.barplot(data=df, x="Discipline", hue="Year", y="Takers")
      

      要添加标签,您可以使用 jezrael 中的 sn-p:

      for p in ax.patches: 
          ax.annotate(np.round(p.get_height(),decimals=2), (p.get_x()+p.get_width()/2., p.get_height()), ha='center', va='center', xytext=(0, 10), textcoords='offset points')
      plt.tight_layout()
      

      【讨论】:

        【解决方案3】:

        首先由DataFrame.pivot 重塑,绘制并最后由this 添加标签:

        ax = df.pivot('Discipline', 'Year','Takers').plot.bar(figsize=(10,10))
        
        for p in ax.patches: 
            ax.annotate(np.round(p.get_height(),decimals=2), (p.get_x()+p.get_width()/2., p.get_height()), ha='center', va='center', xytext=(0, 10), textcoords='offset points')
        

        【讨论】:

        • 谢谢!现在终于更清楚了.. 但是熊猫中有一个函数可以对条形图进行排序吗?也许会显示从左到右下降的条形?
        • 我这样做了,ax = df_group.pivot('Discipline', 'Year','Takers').sort_values('Discipline', ascending=False).plot.bar(title=("Number of Takers per Discipline from 2010 to 2012"), figsize=(20,10)) 但条形图没有排序
        • @Benz 需要ax = df_group.pivot('Discipline', 'Year','Takers').sort_index(ascending=False).plot.bar(title=("Number of Takers per Discipline from 2010 to 2012"), figsize=(20,10))
        • 抱歉,我说错了。我想按接受者而不是纪律列对图表进行排序。但是当我尝试放置 .sot_values('Takers') 时,它会给出错误 KeyError: 'Takers'
        • @Benz - 仍然不确定是否理解,您是否需要绘制第一组如 213、549、567,第二组如 595、612、768?