首页 > 解决方案 > Python 条形图

问题描述

下面是我用来生成条形图的代码,我想在图上方显示相应的值:

import numpy as np
import folium
import pandas as pd
import matplotlib.pyplot as plt
from numpy.ma.bench import xl
from wordcloud import WordCloud,STOPWORDS
import matplotlib as mp
import seaborn as sns

df=pd.read_csv("Topic_Survey_Assignment.csv",index_col=0) # reading csv file
df.sort_values("Very interested", ascending = False)
df_p=(df/2233)*100
df_p=round(df_p,2)
xlist=[]
ylist=[]
c=["#5cb85c","#5bc0de","#d9534f"]
a=df_p.plot(kind='bar',figsize=(20,8),color=c)     # plotting bar plot
plt.xlabel('Subjects',fontsize=14)
plt.ylabel('Percentage of People',fontsize=14)
plt.title('Data Science Statistics',fontsize=20)
plt.legend(fontsize=14)

plt.show(a)
print(xlist)

绘图图像

在此处输入图像描述

标签: pythonmatplotlibseaborndata-science

解决方案


您可以像这样向条形图添加注释:

for p in ax.patches:
    ax.annotate(str(p.get_height()), (p.get_x() + 0.08, p.get_height()), va='bottom', ha='center')

这是一个随机生成数据的示例:

# Generate sample data
c=["#5cb85c","#5bc0de","#d9534f"]
fig, ax = plt.subplots()
df_p.plot(ax = plt.gca(), kind='bar',figsize=(12,8),color=c)     # plotting bar plot
plt.xlabel('Subjects',fontsize=14)
plt.ylabel('Percentage of People',fontsize=14)
plt.title('Data Science Statistics',fontsize=20)
plt.legend(fontsize=14)
plt.tight_layout()

for p in ax.patches:
    ax.annotate(str(p.get_height()), (p.get_x()+0.08, p.get_height()),
                va='bottom', ha='center', weight='bold')

带注释的条形图


推荐阅读