python:本地excel绘制图形

        导入相关模块,先读取本地excel,再根据需求绘制图形

import xlrd
import matplotlib.pyplot as plt
# # 若中文无法正常显示,可使用 Matplotlib 的字体管理器加载中文字体
# import matplotlib.font_manager as fm
# my_font=fm.FontProperties(fname="C:\Windows\Fonts\simkai.ttf")

excel1 = xlrd.open_workbook(r'E:\Wave_Data_wushi\2023\3\0323\230323_08.xlsx')  #xlrd 1.2.0可打开xlsx, 2.0.1只能打开xls
sheet1 = excel1.sheet_by_index(0)                    #打开excel文档第一页
data1 = sheet1.col_values(1,0,100)                   #提取第一页第二列0-100行数据,0和100不填表示提取整列
data2 = sheet1.col_values(2,0,100)
x = sheet1.col_values(0,0,100)

#数据图形绘制,红色为关键字参数,可选填
plt.grid(True,linestyle = '--',alpha = 0.5)           #True,栅格可见,alpha表示栅格透明度,取(0-1),0全透明,1不透明
# plt.plot(x,data1,x,data2)                           #两组数据一起绘制
figure1 = plt.plot(x,data1,c = 'm',linestyle = '--',linewidth = '2',marker = '*',markersize = 5)  #颜色关键字color也可用首字母c,颜色实参也可用英语全称或首字母,如'red'和‘r’
figure2 = plt.plot(x,data2,color = 'c',linestyle = '-',linewidth = '2',marker = 'o',markersize = 5)  #返回值为一个列表
plt.title("回波信号",fontproperties ='simhei',fontsize = 20)        #黑体
plt.xlabel("采样点",fontproperties ='STSong',fontsize = 16)         #宋体
plt.ylabel("回波幅度(mV)",fontproperties ='STKAITI',fontsize = 16)  #楷体       隶体STLITI
plt.yticks([2400,2425,2450,2475,2500,2550,2600],[2400,'',2450,'',2500,2550,2600])  #yticks函数来调整y轴刻度值,第一个列表参数为实际数据值,第二个参数为想要y轴对就显示的字符(一样可不填),不调用函数则自动适应
plt.xticks([138500,138520,138540,138560,138580,138600],['8点1分','8点2分','8点3分','8点4分','8点5分','8点6分'],rotation=315,font='simhei',fontsize=14)

#调用legend函数显示图例,figure1为一个列表,第一个元素表示折线,如果在plot函数中事先写入了label参数,legend函数中的handles、labels参数可不填(推荐此法)
#plt.legend(handles = [figure1[0],figure2[0]],labels = ["数据1","数据2"],loc = "upper right",prop = 'STLITI',fontsize = '20')     #prop中包含了字体大小,设置了prop后fontsize不能生效
font1 = {'family':'STLITI','weight':'normal','size': 14}                                                         #通过定义prop实参来同时修改字体及大小
plt.legend(handles = [figure1[0],figure2[0]],labels = ["数据1","数据2"],loc = "upper right",prop = font1)         #loc:'best'自动选择最佳位置;'lower left':左下
plt.show()

        如果要对  X  轴、Y  轴进行更细致的控制,则可调用  gca()  函数来获取坐标轴信息对象,然后对坐标轴进行控制。比如控制坐标轴上刻度值的位置和坐标轴的位置、颜色、坐标刻度间隔等。

#调用gca()函数来获取坐标轴信息对象
ax = plt.gca()
# 设置将 X 轴的刻度值放在底部 X 轴上
ax.xaxis.set_ticks_position('bottom')
# 设置将 Y 轴的刻度值放在底部 X 轴上
ax.yaxis.set_ticks_position('left')
# 设置右边坐标轴线的颜色(设置为 none 表示不显示)
ax.spines['right'].set_color('none')
# 设置顶部坐标轴线的颜色(设置为 none 表示不显示)
ax.spines['top'].set_color('none')
# 定义底部坐标轴线的位置(放在 70000 数值处)
ax.spines['bottom'].set_position(('data', 2500))
# 设置x、y坐标刻度间隔
x_major_locator = plt.MultipleLocator(100)  #x轴坐标间隔设定为100
y_major_locator = plt.MultipleLocator(10)
ax.xaxis.set_major_locator(x_major_locator)
ax.yaxis.set_major_locator(y_major_locator)

猜你喜欢

转载自blog.csdn.net/chn_zx/article/details/132096543