matplotlib的一个小例子

一个例子:


1
2
3
4
5
6
#-*-coding:utf-8-*-
#文件名: ch.py
def set_ch():
from pylab import mpl
mpl.rcParams['font.sans-serif'] = ['STFangsong'] # 指定默认字体
mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
"""
1-导入Excel文档
2-获得每一列数据
3-第一列作为X轴
4-2~17列作为Y的数据
"""
import ch
ch.set_ch()
from collections import OrderedDict
import xlrd
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
import scipy
from scipy.interpolate import spline
from matplotlib import ticker
font = {
'family':'STFangsong',
'size':12
}
mpl.rc('font',**font)
mpl.rc('figure',autolayout = True,facecolor = 'white')#figure自动使所有内容全部自适应出现在整个图像内
mpl.rc('axes',facecolor = 'white',grid = True)
#导入表格,获取sheet
path = "/Volumes/大白菜/研究生研究课题工作/国网报告整理/20170902严主任数据/实验数据/16路微水变化对比.xlsx"
book_temp = xlrd.open_workbook(path)
sheetName = book_temp.sheet_names()
#建立每一列的数组,数组的元素是1~17列的数据
sheet1 = book_temp.sheet_by_name(sheetName[0])
col_name = []
for i in range(16):
col_name.append('col_data_'+str(i))
col_name[i] = sheet1.col_values(i)[1::15]
#列出X轴的数据
x = np.array([x for x in range(len(col_name[0]))])
xnew = np.linspace(x.min(),x.max(),3000)
#Y轴的数据,使用有序字典
y = OrderedDict()
for i in range(15):
y[i] = col_name[i+1]
ynew = OrderedDict()
for i in range(15):
ynew[i] = spline(x,y[i],xnew)#曲线平滑处理
#进行绘图
fig,ax = plt.subplots(1,1)
for i in range(15):
ax.plot(xnew,ynew[i],label = str(i+1)+"号")
# plt.xlabel("时间")
plt.ylabel("微水($\mu L/L$)")
plt.legend(loc = 0,framealpha = 0.5,fontsize = 8,frameon = False)#修改legend的大小
plt.title("16路微水变化对比图")
#改变X轴坐标的显示
import matplotlib.ticker as ticker
tick_spacing = 15
plt.xticks(x, col_name[0], rotation=15)#改变X轴显示的内容
ax.xaxis.set_major_locator(ticker.MultipleLocator(tick_spacing))#改变X轴显示的密度
fig.set_size_inches(6.3,3.5)
plt.savefig('./images/%s.pdf'%(ax.get_title()),dpi = 300,bbox_inches=None, pad_inches=0.1)
plt.savefig('./images/%s.png'%(ax.get_title()),dpi = 300,bbox_inches=None, pad_inches=0.1)
plt.show()