我正在使用Matplotlib.pyplot库来绘制数据框的条形图。我正在使用下面的代码,并且我正在使用脚本编制层而不是美工层(面向对象的方法)。我已经解决了Artist层的问题,但是我也想使用plt方法解决它。
问题:首先,我格式化图表,然后将百分比放在每个条形图的顶部,但是当我使用注释方法放置百分比时,以前的格式被完全覆盖,并且将百分比应用于为什么会在plt中发生这种情况?
我知道如何使用所有开发人员都喜欢的Artist层解决该问题。但是,我真的想弄清楚为什么plt会将百分比放在旧的图表中,而不是在我所做的更改中。
以下是我的代码供您考虑。我还包含了数据框,因此您可以自己运行它。
import numpy as np
import pandas as pd
df_ds= pd.read_csv('https://cocl.us/datascience_survey_data',header=0,index_col=0)
#Do some changes in my dataframe
df_ds.sort_values(by='Very interested',ascending=False,inplace=True)
df_ds_per=round(df_ds/2233,5)
%matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt
colors_list = ['#5cb85c','#5bc0de','#d9534f']
df_ds_per.plot(kind="bar",figsize=(20, 8),width=0.8,color=colors_list,edgecolor=None)
#Formatting
plt.xticks(fontsize=14)
plt.yticks([])
#Removing the axes
for spine in plt.gca().spines.values():
spine.set_visible(False)
plt.legend(labels=df_ds_per.columns,fontsize= 14)
plt.title("Percentage of Respondents' Interest in Data Science Areas",fontsize= 16)
#Annotation
for p in df_ds_per.plot(kind="bar",figsize=(20, 8),width=0.8,color =
colors_list,edgecolor=None).patches:
width, height = p.get_width(), p.get_height()
x, y = p.get_xy()
plt.annotate('{:.0%}'.format(height), (x, y + height + 0.01))
plt.show()
结果是两个图,第一个图具有所有格式,但没有百分比,第二个图仅具有百分比,没有格式。 我知道如何通过将对象轴设置为与情节相等来解决艺术家层中的问题,所以请仅使用plt帮助我。
感谢很多团队。很高兴来到这里