Matplotlib练习7:直方图

#生成0~9的数据
x = np.arange(10)
#2的x次方+10
y = 2**x + 10
plt.bar(x, y)

效果图

plt.bar(x, -y)

在这里插入图片描述

改变颜色

#facecolor直方颜色,edgecolor直方边缘颜色
plt.bar(x, y, facecolor='#9999ff', edgecolor='white')

在直方的上方标数据

#为直方上填数据
#zip把x,y结合成一个整体 for中用zip 同时读取一个x和一个y
#text(x, y)文本位置坐标
for x, y in zip(x, y):
    plt.text(x, y, '%.2f' % y, ha='center', va='bottom')

效果图

va='bottom’修改为va=‘top’

for x, y in zip(x, y):
    plt.text(x, y, '%.2f' % y, ha='center', va='top')

效果图

完整代码

import matplotlib.pyplot as plt
import numpy as np
#生成0~9的数据
x = np.arange(10)
#2的x次方+10
y = 2**x + 10
plt.bar(x, y, facecolor='#9999ff', edgecolor='white')
#为直方上填数据
#zip把x,y结合成一个整体 for中用zip 同时读取一个x和一个y
#text(x, y)文本位置坐标
for x, y in zip(x, y):
    plt.text(x, y, '%.2f' % y, ha='center', va='bottom')

plt.show()

猜你喜欢

转载自blog.csdn.net/weixin_48524215/article/details/111809392