100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > python柱状图加百分比_python matplotlib 为柱状图添加百分比

python柱状图加百分比_python matplotlib 为柱状图添加百分比

时间:2024-06-15 06:07:05

相关推荐

python柱状图加百分比_python matplotlib 为柱状图添加百分比

背景

最近使用python matplotlib绘制柱状图时,想要更清晰地查看每一项占总数的百分比,在搜索后发现matplotlib.pyplot.bar方法并没有提供这个参数,于是自己尝试实现了这个功能。

实现方法

实现方法很简单,利用plt.text方法在柱状图的合适位置添加计算后的百分比数值即可,添加的位置这里选择了柱状图顶端的合适位置,更改plt.text(x, y + y_max / 20, str(round(percentage[x], 2)), ha='center')这行代码里的参数也可很容易实现在柱状图的中间等位置进行绘制添加。

详细代码如下:

import matplotlib.pyplot as plt

def bar_with_percentage_plot(x_list, y_list):

# 绘图参数, 第一个参数是x轴的数据, 第二个参数是y轴的数据,

# 第三个参数是柱子的大小, 默认值是1(值在0到1之间), color是柱子的颜色, alpha是柱子的透明度

plt.bar(range(len(x_list)), y_list, 0.4, color='r', alpha=0.8)

# 添加轴标签

plt.ylabel('y轴')

# 标题

plt.title('柱状图添加百分比')

# 添加刻度标签

plt.xticks(range(len(x_list)), x_list)

# 设置Y轴的刻度范围

y_max = max(y_list) + max(y_list) / 6

plt.ylim([0, y_max])

y_sum = sum(y_list)

percentage = [x / y_sum for x in y_list]

# 为每个条形图添加数值标签

for x, y in enumerate(y_list):

plt.text(x, y + y_max / 20, str(round(percentage[x], 2)), ha='center')

# 显示图形

plt.show()

if __name__ == '__main__':

x_list = ['A', 'B', 'C', 'D']

y_list = [110, 30, 200, 150]

bar_with_percentage_plot(x_list, y_list)

最终显示效果如下图所示:

image.png

参考

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。