问题
I am using Matplotlib.pyplot library in order to draw a barchart of a dataframe.I am using the code below and i am using the scripting layer instead of using the artist layer(object oriented method). I have solve my problem with the artist layer however i want to solve it with the plt method as well.
PROBLEM:Firsty I format the plot and then I want to put percentages in the top of each barchart ,however when I do the annotation method to put the percentages the previous formatting is overwritten-completely gone and the percentages are applied to the old plot.Why this happened in plt?
I know how to solve it using the Artist layer which is preferred by all developers. However I really want to figure out why plt puts the percentages in the old barchart and not in the one that I have done the changes.
Below is my code for your consideration. I have also included the dataframe so you can run it by yourself.
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()
The results are two plots with the first one having all the formats but not the percentages and the second one has only the percentages without the formats. I know how to solve it in artist layer by setting an object ax equal with the plot so please help my using only plt.
Thanks a lot team.Happy to be here
来源:https://stackoverflow.com/questions/56139715/annotate-deleted-my-previous-formatting-in-plt