如何绘制和注释分组的条形图

时间:2020-08-19 19:11:51

标签: python pandas matplotlib

我遇到了一个关于Python中matplotlib的棘手问题。我想用几个代码创建一个分组的条形图,但是该图表出错。你能给我一些建议吗?代码如下。

def __forward_ref_repr__(self: ref) -> str:
    return str(self.__forward_arg__)


setattr(ref, "__repr__", __forward_ref_repr__)

此代码模块的输出确实是一团糟。但是我期望的效果应该类似于图片中的条形图。您能告诉我代码中哪一点不正确吗?

enter image description here

1 个答案:

答案 0 :(得分:2)

  • 在给出当前代码的情况下,JohanCw = 0.8 / 3的评论将解决此问题。
  • 但是,使用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')

enter image description here