1、x 表示数量,y 表示名字
1 import matplotlib.pyplot as plt 2 3 4 dic = {‘a‘: 22, ‘b‘: 10, ‘c‘: 6, ‘d‘: 4, ‘e‘: 2, ‘f‘: 10, ‘g‘: 24, ‘h‘: 16, ‘i‘: 1, ‘j‘: 12} 5 s = sorted(dic.items(), key=lambda x: x[1], reverse=False) # 对dict 按照value排序 True表示翻转 ,转为了列表形式 6 print(s) 7 x_x = [] 8 y_y = [] 9 for i in s: 10 x_x.append(i[0]) 11 y_y.append(i[1]) 12 13 x = x_x 14 y = y_y 15 16 fig, ax = plt.subplots() 17 ax.barh(x, y, color="deepskyblue") 18 labels = ax.get_xticklabels() 19 plt.setp(labels, rotation=0, horizontalalignment=‘right‘) 20 21 for a, b in zip(x, y): 22 plt.text(b+1, a, b, ha=‘center‘, va=‘center‘) 23 ax.legend(["label"],loc="lower right") 24 25 plt.rcParams[‘font.sans-serif‘] = [‘SimHei‘] # 用来正常显示中文标签 26 plt.ylabel(‘name‘) 27 plt.xlabel(‘数量‘) 28 plt.rcParams[‘savefig.dpi‘] = 300 # 图片像素 29 plt.rcParams[‘figure.dpi‘] = 300 # 分辨率 30 plt.rcParams[‘figure.figsize‘] = (15.0, 8.0) # 尺寸 31 plt.title("title") 32 33 plt.savefig(‘D:\\result.png‘) 34 plt.show()
2、x 表示名字,y 表示数量,多重组合
import matplotlib.pyplot as plt import numpy as np x = [‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘, ‘g‘, ‘h‘, ‘i‘, ‘j‘] y1 = [6, 5, 8, 5, 6, 6, 8, 9, 8, 10] y2 = [5, 3, 6, 4, 3, 4, 7, 4, 4, 6] y3 = [4, 1, 2, 1, 2, 1, 6, 2, 3, 2] plt.bar(x, y1, label="label1", color=‘red‘) plt.bar(x, y2, label="label2",color=‘orange‘) plt.bar(x, y3, label="label3", color=‘lightgreen‘) plt.xticks(np.arange(len(x)), x, rotation=0, fontsize=10) # 数量多可以采用270度,数量少可以采用340度,得到更好的视图 plt.legend(loc="upper left") # 防止label和图像重合显示不出来 plt.rcParams[‘font.sans-serif‘] = [‘SimHei‘] # 用来正常显示中文标签 plt.ylabel(‘数量‘) plt.xlabel(‘name‘) plt.rcParams[‘savefig.dpi‘] = 300 # 图片像素 plt.rcParams[‘figure.dpi‘] = 300 # 分辨率 plt.rcParams[‘figure.figsize‘] = (15.0, 8.0) # 尺寸 plt.title("title") plt.savefig(‘D:\\result.png‘) plt.show()
原文:https://www.cnblogs.com/BackingStar/p/10986955.html