python設定X軸刻度個數,刻度轉換成其他文字,刻度旋轉
阿新 • • 發佈:2019-01-25
#-*- coding: utf-8 -*- #--------------------------------------------------- import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import MultipleLocator, FormatStrFormatter import csv #--------------------------------------------------- def data_process(): # excelfile = xlrd.open_workbook(r'C:\Users\laich\Desktop\harda.xlsx') excelfile = csv.reader(open(r'C:\Users\laich\Desktop\scope_data.csv')) data = [] for stu in excelfile: data.append(stu) dates = get_date(0,data) ia = get_num(1,data) ib = get_num(2,data) ic = get_num(3,data) ua = get_num(4,data) ub = get_num(5,data) uc = get_num(6,data) ax = plt.subplot(111) #注意:一般都在ax中設定,不再plot中設定 # plt.plot(dates,ia,'r') # plt.plot(dates,ib,'y') # plt.plot(dates,ic,'b') plt.plot(ia,'r') plt.plot(ib,'y') plt.plot(ic,'b') #設定主刻度標籤的位置,標籤文字的格式 xmajorLocator = MultipleLocator(2500) #將x主刻度標籤設定為n的倍數 xmajorFormatter = FormatStrFormatter('%1.1f') #設定x軸標籤文字的格式 ax.xaxis.set_major_locator(xmajorLocator) ax.xaxis.set_major_formatter(xmajorFormatter) # plt.xticks([0,4999,9999,14999,19999],[dates[0],dates[4999],dates[9999],dates[14999],dates[19999]]) plt.xticks([0,2499,4999,7499,9999,12499,14999,17499,19999],[dates[0],dates[2499],dates[4999],dates[7499],dates[9999],dates[12499],dates[14999],dates[19999]]) plt.legend(['ia','ib','ic']) plt.xticks(rotation=15) plt.show() def get_date(ids,data): getnum = [] row,col = np.shape(data) for i in range(1,row): getnum.append(data[i][ids]) return getnum def get_num(ids,data): getnum = [] row,col = np.shape(data) for i in range(1,row): getnum.append(float(data[i][ids])) return getnum if __name__ == '__main__': data_process()
主要函式在於
#設定主刻度標籤的位置,標籤文字的格式 xmajorLocator = MultipleLocator(2500) #將x主刻度標籤設定為n的倍數 xmajorFormatter = FormatStrFormatter('%1.1f') #設定x軸標籤文字的格式 ax.xaxis.set_major_locator(xmajorLocator) ax.xaxis.set_major_formatter(xmajorFormatter)
這裡MultipleLocator用於設定間隔多少個刻度顯示一個刻度值
plt.xticks([0,2499,4999,7499,9999,12499,14999,17499,19999],[dates[0],dates[2499],dates[4999],dates[7499],dates[9999],dates[12499],dates[14999],dates[19999]])
函式xticks用於將數值刻度轉換成任意字元刻度
plt.xticks(rotation=15)
將顯示的刻度旋狀防止重疊
顯示效果如下