每天記錄一下編程中遇到的問題
1)簡單柱形圖
先插入代碼,如下。
import matplotlib.pyplot as plt import numpy as np x_labels = ['2021-2-12', '2021-2-13', '2021-2-14', '2021-2-15', '2021-2-16', '2021-2-17', '2021-2-18', '2021-2-19'] guangfu = [1, 7, 4, 2, 20, 5, 8, 10] jungong = [2, 19, 5, 10, 8, 4, 30, 14] zhengquan = [0.5, 16, 9, 10, 2, 18, 30, 11] # 這兩行代碼解決 plt 中文顯示的問題 plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False # X軸位置 x = np.arange(len(x_labels)) # 柱圖大小 width = 0.2 # 創建圖形 fig, ax = plt.subplots() ax.bar(x + width, guangfu, width, label='光伏概念') ax.bar(x + width*2, jungong, width, label='軍工概念') ax.bar(x + width*3, zhengquan, width, label='證券概念') # Y軸標題 ax.set_ylabel('每日資金入量/億') ax.set_title('概念股資金動賬') # X軸坐標顯示,x + width*2 標識X軸刻度所在位置 ax.set_xticks(x + width*2) ax.set_xticklabels(x_labels) # 顯示右上角圖例 ax.legend() # 自動調整子圖參數以提供指定的填充。多數情況下沒看出來區別 fig.tight_layout() plt.show()
相關代碼解釋如上圖。
執行結果展示:
2)進階柱形圖
相較於第一個,增加了autolabel函數,來對柱子大小標記,話不多說,如下圖顯示。
import matplotlib.pyplot as plt import numpy as np x_labels = ['2021-2-12', '2021-2-13', '2021-2-14', '2021-2-15', '2021-2-16', '2021-2-17', '2021-2-18', '2021-2-19'] guangfu = [1, 7, 4, 2, 20, 5, 8, 10] jungong = [2, 19, 5, 10, 8, 4, 30, 14] zhengquan = [0.5, 16, 9, 10, 2, 18, 30, 11] # 這兩行代碼解決 plt 中文顯示的問題 plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False # X軸位置,X軸刻度的大小 x = np.arange(0, 16, 2) # 柱圖大小 width = 0.4 # 創建圖形 fig, ax = plt.subplots() rects1 = ax.bar(x + width, guangfu, width, label='光伏概念') rects2 = ax.bar(x + width*2, jungong, width, label='軍工概念') rects3 = ax.bar(x + width*3, zhengquan, width, label='證券概念') # Y軸標題 ax.set_ylabel('每日資金入量/億') ax.set_title('概念股資金動賬') # X軸坐標顯示,x + width*2 標識X軸刻度所在位置 ax.set_xticks(x + width*2) ax.set_xticklabels(x_labels) # 顯示右上角圖例 ax.legend() # 在*rects*的每個欄的上方附加一個文本標簽,顯示它的高度 def autolabel(rects): for rect in rects: height = rect.get_height() ax.annotate('{}'.format(height), xy=(rect.get_x() + rect.get_width() / 2, height), xytext=(0, 3), # 3 points vertical offset textcoords="offset points", ha='center', va='bottom') autolabel(rects1) autolabel(rects2) autolabel(rects3) # 自動調整子圖參數以提供指定的填充。多數情況下沒看出來區別 fig.tight_layout() plt.show()
執行結果展示:
參考鏈接:https://matplotlib.org/3.1.1/api/pyplot_summary.html