简体   繁体   English

使用 matplotlib 绘制具有多个观察值的条形图

[英]Plotting a bar graph with multiple observations using matplotlib

Suppose I have a data frame df假设我有一个数据框df

df =

Name   Percentage  No. of Subjects
Sai    90          4
Kiran  84          2
Karan  26          5
Teja   70          5

I am interested in plotting a bar graph showing the df['No. of Subjects']我有兴趣绘制一个显示df['No. of Subjects'] df['No. of Subjects'] on the x-axis, df['Percentage'] on the y-axis and df['Name'] as Bars with a legend. x 轴上df['No. of Subjects'] ,y 轴上的df['Percentage']df['Name']作为带有图例的条形。

Expected Schematic Output looks like:):预期的原理图 Output 看起来像:):

在此处输入图像描述

import pandas as pd
import seaborn as sns

df = pd.DataFrame( [{"Name":"Sai", "Percentage":90, "No. of Subjects":4},
{"Name":"Kiran", "Percentage":84, "No. of Subjects":2},
{"Name":"Karan", "Percentage":26, "No. of Subjects":5},
{"Name":"Teja", "Percentage":70, "No. of Subjects":5}] ) 

ax = sns.barplot(x="Name", y="Percentage", hue="No. of Subjects", data=df, dodge=False)

#You can try without those next lines, but need them on my mac
import matplotlib.pyplot as plt 
plt.show()

It make more sense to plot with name in the x axis.对于在 x 轴上带有名称的 plot 更有意义。 As you have 2 students with the same No of subjects, the function barplot will understand it in a different way.由于您有 2 个学生的科目数相同,因此 function 条形图将以不同的方式理解它。

在此处输入图像描述

Please have a look at the very good doc of seaborn for bar plot , it is full of exemples !请看一下seaborn for bar plot 的非常好的文档,它充满了例子!

Best, R最好的,R

A seaborn barplot can be used to draw the bars. seaborn 条形图可用于绘制条形图。 The hue parameter is responsible to color each bar and create entries for an accompanying legend with the names.色调参数负责为每个条着色并为带有名称的随附图例创建条目。

To get the 'No.要获得“不”。 of Subjects' in the xtick labels, they can be set explicitly. xtick 标签中的主题,它们可以显式设置。

import pandas as pd
from matplotlib import pyplot as plt
import seaborn as sns

df = pd.DataFrame({'Name': ['Sai', 'Kiran', 'Karan', 'Teja'],
                   'Percentage': [90, 84, 26, 70],
                   'No. of Subjects': [4, 2, 5, 5]})
ax = sns.barplot(x='Name', y='Percentage', hue='Name', dodge=False, data=df)
ax.set_xticklabels(df['No. of Subjects'])
ax.set_xlabel('No. of Subjects')
ax.set_ylim(0, 100)
ax.legend(loc='upper left', bbox_to_anchor=(1.01, 1.05))
for i, perc in enumerate(df['Percentage']):
    ax.text(i, perc, f'{perc:.0f} %\n', ha='center', va='center', size=15)
plt.tight_layout()
plt.show()

结果图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM