How to plot and annotate a grouped bar chart

后端 未结 1 575
粉色の甜心
粉色の甜心 2020-12-22 04:30

I came across a tricky issue about the matplotlib in Python. I want to create a grouped bar chart with several codes, but the chart goes wrong. Could you please offer me som

相关标签:
1条回答
  • 2020-12-22 04:58
    • The comment from JohanC, w = 0.8 / 3 will resolve the issue, given the current code.
    • However, generating the plot can be accomplished more easily with pandas.DataFrame.plot
    import pandas as pd
    import matplotlib.pyplot as plt
    
    # given the following code to create the dataframe
    file="https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DV0101EN/labs/coursera/Topic_Survey_Assignment.csv"
    df=pd.read_csv(file,index_col=0)
    
    df.sort_values(by=['Very interested'], axis=0,ascending=False,inplace=True)
    
    df['Very interested']=df['Very interested']/2233
    df['Somewhat interested']=df['Somewhat interested']/2233
    df['Not interested']=df['Not interested']/2233
    
    # your colors
    colors = ['#5cb85c', '#5bc0de', '#d9534f']
    
    # plot with annotations is probably easier
    p1 = df.plot.bar(color=colors, figsize=(20, 8), ylabel='Percentage', title="The percentage of the respondents' interest in the different data science Area")
    p1.set_xticklabels(p1.get_xticklabels(), rotation=0)
    
    for p in p1.patches:
        p1.annotate(f'{p.get_height():0.2f}', (p.get_x() + p.get_width() / 2., p.get_height()), ha = 'center', va = 'center', xytext = (0, 10), textcoords = 'offset points')
    

    0 讨论(0)
提交回复
热议问题