DW第四关收获
1.了解了关于子图文本、注解、标签的修改方式,以及xy轴标签、整体图例的函数
2.初步掌握了barh的用法,可以在画布上实现横向柱状图
3.接口的变化好像不多,但是运用起来相对灵活。同时在本次学习中,更深刻的认识到在画图前,需要做好数据处理工作,为可视化打好基础。
思考题:
请尝试使用两种方式模仿画出下面的图表(重点是柱状图上的标签),本文学习的text方法和matplotlib自带的柱状图标签方法bar_label
一、
import numpy as np
import matplotlib.pyplot as plt
names = ['Tom', 'Dick', 'Harry', 'Slim', 'Jim']
idx = np.arange(5)
values = 8 + 8*np.random.rand(1,5)
bias = np.random.rand(1, 5).round(2)[0]
values = values.round(1)[0]
fig = plt.figure(figsize = (16, 8))
ax = fig.add_subplot(111)
plt.barh(names, values, xerr = bias)
ax.set_title('How fast do you want to go?')
ax.set_xlabel('Performance')
ax.xaxis.label.set_size(16)
ax.yaxis.label.set_size(16)
ax.xaxis.set_ticks(np.arange(0, 20, 2));
for i in range(5):
ax.text(values[i] + bias[i] + 1, names[i], '±' + str(bias[i]), fontsize = 13, horizontalalignment = 'center')
二、
import matplotlib.pyplot as plt
import numpy as np
fig,ax = plt.subplots()
people = ('Jim','Slim','Harry','Dick','Tom')
performance = 8 + np.random.rand(len(people))
error = np.random.rand(len(people)).round(2)
plt.barh(people,performance,xerr = error)
fig.suptitle('How fast do you wang to go today',fontsize = 14) # 标题
ax.set_xlabel('Performance')
ax.xaxis.set_ticks(np.arange(0,20,2))
for i in range(0,5):
ax.text(performance[i] + error[i] + 1,people[i],'±'+str(error[i]),fontsize = 10,horizontalalignment = 'center',color = 'blue')
plt.show()
三、
import numpy as np
import matplotlib.pyplot as plt
names = ['Tom', 'Dick', 'Harry', 'Slim', 'Jim']
idx = np.arange(5)
values = 8 + 8*np.random.rand(1,5)
bias = np.random.rand(1, 5).round(2)[0]
values = values.round(1)[0]
fig = plt.figure(figsize = (12, 8))
ax = fig.add_subplot(111)
plt.bar(names, values, orientation = 'vertical', yerr = bias)
ax.set_xticklabels(names, fontsize = 14)
ax.set_title('How fast do you want to go?')
ax.set_xlabel('Performance')
ax.xaxis.label.set_size(16)
ax.yaxis.label.set_size(16) # 设置坐标轴文字大小
for i in range(5):
ax.text(names[i], values[i] + bias[i] + 0.2, '±' + str(bias[i]), fontsize = 14, horizontalalignment = 'center')