如何解决如何在Python中绘制水平条形图的百分比标签?
考虑到以下水平条形图代码,有人可以帮我按百分比绘制x轴标签吗?
很难找到,因为我想要一个没有x轴标签和刻度的更简单的图表。
[水平条形图] [1]
# Plot the figure size
plt.figure(figsize= (8,6))
# New variable and plot the question of the data frame in a normalized in a horizontal bar chat.
ax1 = df[q1].value_counts(normalize=True).sort_values().plot(kind="barh",color='#fd6a02',width=0.75,zorder=2)
# Draw vague vertical axis lines and set lines to the back of the order
vals = ax1.get_xticks()
for tick in vals:
ax1.axvline(x=tick,linestyle='dashed',alpha=0.4,color = '#d3d3d3',zorder=1)
# Tot3als to produce a composition ratio
total_percent = df[q1].value_counts(normalize=True) *100
# Remove borders
ax1.spines['right'].set_visible(False)
ax1.spines['top'].set_visible(False)
ax1.spines['left'].set_visible(False)
ax1.spines['bottom'].set_visible(False)
# Set the title of the graph inline with the Y axis labels.
ax1.set_title(q1,weight='bold',size=14,loc = 'left',pad=20,x = -0.16)
# ax.text(x,y,text,color)
for i,val in enumerate(total):
ax1.text(val - 1.5,i,str("{:.2%}".format(total_percent),color="w",fontsize=10,zorder=3)
# Create axis labels
plt.xlabel("Ratio of Responses",labelpad=20,size=12)
每次我出现EOF错误。有人可以帮忙吗?
解决方法
它不是基于您的代码,但是我将从官方参考中定制答案。
可以通过ax.text()
实现这一点,这是一个循环过程。
import matplotlib.pyplot as plt
import numpy as np
# Fixing random state for reproducibility
np.random.seed(19680801)
plt.rcdefaults()
fig,ax = plt.subplots()
# Example data
people = ('Tom','Dick','Harry','Slim','Jim')
y_pos = np.arange(len(people))
performance = 3 + 10 * np.random.rand(len(people))
ax.barh(y_pos,performance,align='center')
ax.set_yticks(y_pos)
ax.set_yticklabels(people)
ax.invert_yaxis() # labels read top-to-bottom
ax.set_xlabel('Performance')
ax.set_title('How fast do you want to go today?')
# Totals to produce a composition ratio
total = sum(performance)
# ax.text(x,y,text,color)
for i,val in enumerate(performance):
ax.text(val - 1.5,i,str("{:.2%}".format(val/total)),color="w",fontsize=10)
plt.show()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。