我有以下代码,可以创建水平条形图:
data = pandas.read_csv('C:/py/matplotlib/02-BarCharts/data.csv')
responders_id = data['Responder_id']
langs_worked_with = data['LanguagesWorkedWith']
languages = Counter()
for reponse in langs_worked_with:
languages.update(reponse.split(";"))
langs = []
langs_users_num = []
for language in languages.most_common(15):
langs.append(language[0])
langs_users_num.append(language[1])
langs.reverse()
langs_users_num.reverse()
plt.barh(langs, langs_users_num)
plt.tight_layout()
plt.show()
运行上面的代码后,我得到了:
表示此图表的数据是从stackoverflow解析的,并且stackoverflow中的同一图表如下所示。如何修改上面的代码以增加百分比,如下所示。
请帮助我。谢谢
答案 0 :(得分:1)
这是一种方法。我选择了一些样本数据。这个想法是
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
total = 90000
langs = ['C', 'C++', 'Java', 'Python']
langs_users_num = np.array([32000, 40000, 50000, 60000])
percent = langs_users_num/total*100
new_labels = [i+' {:.2f}%'.format(j) for i, j in zip(langs, percent)]
plt.barh(langs, langs_users_num, color='lightskyblue', edgecolor='blue')
plt.yticks(range(len(langs)), new_labels)
plt.tight_layout()
for spine in ax.spines.values():
spine.set_visible(False)
ax.axes.get_xaxis().set_visible(False)
ax.tick_params(axis="y", left=False)
plt.show()