300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > python中plot柱状图-python matplotlib模块: bar(柱状图)

python中plot柱状图-python matplotlib模块: bar(柱状图)

时间:2023-10-12 22:01:13

相关推荐

python中plot柱状图-python matplotlib模块: bar(柱状图)

plt模块的bar方法可以帮助我们绘制竖着的柱状图。

功能非常强大, 使用起来非常简单, 详细注释放在源码。

其中各种颜色的hex值可以从:

各种颜色hex值获取

源码:

# coding=utf-8

from matplotlib import pyplot as plt

import numpy as np

plt.style.use('fivethirtyeight')

# 可以查看所有可供使用的展示风格

# print(plt.style.available)

dev_x = [25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35]

# 创建一维的等差数列, 是一个ndarray对象, 类似于[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ....]

x_indexes = np.arange(len(dev_x))

dev_y = [38496, 42000, 46752, 49320, 53200,

56000, 62316, 64928, 67317, 68748, 73752]

py_dev_y = [45372, 48876, 53850, 57287, 63016,

65998, 70003, 70000, 71496, 75370, 83640]

js_dev_y = [37810, 43515, 46823, 49293, 53437,

56373, 62375, 66674, 68745, 68746, 74583]

# 设置每个柱状体(bar)的宽度

width = 0.25

# 这个数据集设置的柱状体颜色是绿色, 放置在x轴的0-0.25, 1-0.25, 2-0.25, ...位置上(也就是在中间柱体紧邻的左边), 宽度0.25

plt.bar(x_indexes - width, dev_y, width=width,

color='#18F904', label='all_devs')

# 这个数据集设置的柱状体颜色是红色, 放置在x轴的0, 1, 2, 3, 4, 5, ...位置上, 宽度0.25

plt.bar(x_indexes, py_dev_y, width=width, color='#F90404', label='Python')

# 这个数据集设置的柱状体颜色是蓝色, 放置在x轴的0+0.25, 1+0.25, 2+0.25, ...位置上(也就是在中间柱体紧邻的右边), 宽度0.25

plt.bar(x_indexes + width, js_dev_y, width=width,

color='#0451F9', label='JavaScript')

# 将柱状体的x轴原本的下标映射到新的标签上

plt.xticks(ticks=x_indexes, labels=dev_x)

# 设置标题, x轴的标签, y轴的标签

plt.title('First bar')

plt.xlabel('Developer ages')

plt.ylabel("Developer's annual salary")

# 设置每一组数据展示图象的标签(用以区分不同的数据图象), 不加legend方法, 前面就算设置了lebel=XXX也没用

plt.legend()

# 紧致最后的图形, 更美观

plt.tight_layout()

plt.show()

运行结果:

图片.png

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