本文主要使用matplotlib,實現雙縱軸座標的圖表繪製。筆者python版本爲2.7.15。html
某個有這麼一個成績表,分別是名字,本次成績以及進步幅度,如今須要把這個成績單轉爲這樣一個圖表:python
橫軸是同窗姓名,成績用直方圖表示,進步幅度用折線圖表示,他們公用同一個橫軸。api
姓名函數 |
本次成績字體 |
進步幅度spa |
小給code |
88orm |
23%htm |
小人blog |
78 |
10% |
小民 |
90 |
5% |
小一 |
66 |
9% |
小個 |
80 |
22% |
小膠 |
48 |
5% |
小帶 |
77 |
19% |
搬運官網的說明:
Create a twin Axes sharing the xaxis
Create a new Axes instance with an invisible x-axis and an independent y-axis positioned opposite to the original one (i.e. at right). The x-axis autoscale setting will be inherited from the original Axes.
大意就是使用這個函數,在原來的座標系中新建一個共享x軸的雙胞胎座標系,相似的還有twiny。
#-*- coding:utf-8 -*- import numpy as np import matplotlib.pyplot as plt import matplotlib.ticker as mtick def main(): plt.rcdefaults() plt.rcParams['font.sans-serif'] = ['SimHei'] # 指定默認字體 plt.rcParams['axes.unicode_minus'] = False # 解決保存圖像是負號'-'顯示爲方塊的問題 info_list = [(u"小給", 88, 23), (u"小人", 78, 10), (u"小民", 90, 5), (u"小一", 66, 9), (u"小個", 80, 22), (u"小膠", 48, 5), (u"小帶", 77, 19)] positions = np.arange(len(info_list)) names = [row[0] for row in info_list] scores = [row[1] for row in info_list] proges = [row[2] for row in info_list] fig, ax1 = plt.subplots() # 成績直方圖 ax1.bar(positions, scores, width=0.6, align='center', color='r', label=u"成績") ax1.set_xticks(positions) ax1.set_xticklabels(names) ax1.set_xlabel(u"名字") ax1.set_ylabel(u"成績") max_score = max(scores) ax1.set_ylim(0, int(max_score * 1.2)) # 成績標籤 for x,y in zip(positions, scores): ax1.text(x, y + max_score * 0.02, y, ha='center', va='center', fontsize=13) # 變更折線圖 ax2 = ax1.twinx() ax2.plot(positions, proges, 'o-', label=u"進步幅度") max_proges = max(proges) # 變化率標籤 for x,y in zip(positions, proges): ax2.text(x, y + max_proges * 0.02, ('%.1f%%' %y), ha='center', va= 'bottom', fontsize=13) # 設置縱軸格式 fmt = '%.1f%%' yticks = mtick.FormatStrFormatter(fmt) ax2.yaxis.set_major_formatter(yticks) ax2.set_ylim(0, int(max_proges * 1.2)) ax2.set_ylabel(u"進步幅度") # 圖例 handles1, labels1 = ax1.get_legend_handles_labels() handles2, labels2 = ax2.get_legend_handles_labels() plt.legend(handles1+handles2, labels1+labels2, loc='upper right') plt.show() if __name__ == '__main__': main()
1. matplotlib圖例:api example code: two_scales.py
(完)