1.上下两组比对。
# 显示高度
def autolabel(rects1, rects2):
i = 0
for rect1 in rects1:
rect2 = rects2[i]
i += 1
height = rect1.get_height() + rect2.get_height()
plt.text(rect1.get_x()+rect1.get_width()/2. - 0.1, 1.03*height, '%s' % int(height))
name_list = ['A', 'B', 'C', 'D']
num_list = [10, 15, 16, 28]
num_list2 = [10, 12, 18, 26]
z1 = plt.bar(range(len(num_list)), num_list, label='1', fc='b')
z2 = plt.bar(range(len(num_list)), num_list2, bottom=num_list, label='2', tick_label=name_list, fc='g')
autolabel(z1, z2)
plt.legend()
plt.savefig('figure.pdf', bbox_inches='tight')
plt.show()
2.左右两组比对。
name_list = ['A', 'B', 'C', 'D']
num_list = [10, 15, 16, 28]
num_list2 = [10, 12, 18, 26]
x = list(range(len(num_list)))
total_width, n = 0.8, 2
width = total_width / n
plt.bar(x, num_list, width=width, label='1', fc='b')
for i in range(len(x)):
x[i] += width
plt.bar(x, num_list2, width=width, label='2', tick_label=name_list, fc='g')
plt.legend()
plt.show()
3.水平柱状图
import matplotlib.pyplot as plt
# 数据准备
categories = ['Apple', 'Red apple', 'Black A.', 'White A.']
values = [10, 15, 7, 18]
# 创建水平柱状图
plt.barh(categories, values) # 使用categories作为x轴,values作为y轴(在barh中颠倒)
plt.xlabel('Qty') # x轴标签
plt.ylabel('Type') # y轴标签
plt.title('Title') # 图表标题
plt.savefig('figure4.pdf', bbox_inches='tight')
plt.show() # 显示图表