python设置X轴刻度个数,刻度转换成其他文字,刻度旋转
程序员文章站
2022-03-10 21:24:03
...
#-*- 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)
将显示的刻度旋状防止重叠
显示效果如下