python繪圖demo實現(xiàn)流程介紹
前言
冒個泡泡,好久沒有冒泡泡了,那么今天的話就淺淺水一下博文吧。任務(wù)是這樣的,將Excel當中的數(shù)據(jù),把它放到咱們的matlpolitlib里面去畫個圖。
數(shù)據(jù)是這樣子的:

這里面有很多sheet,然后還有對應(yīng)的點的坐標。要最終實現(xiàn)的效果就是:

并且我們還需要符合規(guī)范:

這樣的話圖片才不會失真。BOSS不催,小爺不寫(狗頭)
實現(xiàn)
那么這里的話就是咱們的實現(xiàn)了這個Excel的讀取,然后是繪制圖片。
讀取數(shù)據(jù)
首先是讀取數(shù)據(jù),這部分相當簡單,就在初始化做了。
def __init__(self,file_path,pic_name=None,
legend_names=None,padx=0,pady=1,
save_path_pre="./pic"
):
"""
默認存儲的圖片為4K,600dpi
:param file_path:
:param pic_name:
:param legend_names:
:param padx:
:param pady:
:param save_path_pre:
"""
self.xl_file = xlrd.open_workbook(file_path)
self.sheet_names = self.xl_file.sheet_names()
self.legend_names = None
self.setTrans = False
self.setFig = False
self.join = False
self.padx = padx
self.pady = pady
self.save_path_pre = save_path_pre
if(pic_name):
self.pic_name = pic_name
else:
self.pic_name = self.sheet_names
if(legend_names and padx==None):
self.legend_names=legend_names
elif(legend_names==None):
sheet1 = self.xl_file.sheets()[0]
sheet1_cols = sheet1.col_values(padx)
self.legend_names = sheet1_cols[pady:]
elif(legend_names!=None):
self.legend_names = legend_names
else:
raise Exception("請檢查格式,或者參數(shù)設(shè)置")這里我解釋一下這幾個參數(shù)的含義
默認存儲的圖片為4K,600dpi
:param file_path:
:param pic_name:
:param legend_names: 圖例的名字
:param padx: 數(shù)據(jù)是從哪一個列開始的
:param pady: 哪一個行開始的
:param save_path_pre:
"""
例如剛剛的例子,是在第1行第1列開始的,下標0開始。
如果沒有指定那個圖例說明的話,那么代碼就會直接取pady那一列的數(shù)據(jù)作為圖例。
繪圖
這個繪圖的話非常簡單,就是直接使用那個plt,讀取好數(shù)據(jù)就好了。
def creatPic(self,legend_loc='upper right',multiple=40,
padding=10000,width=4096,height=3112
):
"""
:param legend_loc: 圖例的說明
:return:
"""
if(self.setFig and self.setFig):
for sheet_index in range(len(self.xl_file.sheet_names())):
sheet = self.xl_file.sheets()[sheet_index]
self.plt = self.creatFigure()
#按照行進行讀取
for row in range(self.pady,len(self.legend_names)+self.pady):
row_data_y = [self.transform(float(data),padding) for data in sheet.row_values(row)[self.padx+1:]]
row_data_x = [x*multiple for x in range(len(row_data_y))]
label_name = self.legend_names[row-self.pady]
self.plt.plot(row_data_x,row_data_y,label=label_name)
plt.legend()
save_path = self.save_path_pre+"./"+self.pic_name[sheet_index]+".jpg"
self.plt.savefig(save_path,
dpi=600, bbox_inches='tight'
)
self.changeImgSiz(save_path)
self.plt.pause(0.05)
else:
raise Exception("請先設(shè)置數(shù)據(jù)轉(zhuǎn)換方式以及繪圖")
這里的話還有一點就是有一個修改圖片尺寸的代碼,以為畫布尺寸和那個實際圖片尺寸還是有點區(qū)別的。這個看著改吧,當然你可以選擇保存為png,但是這樣的話,x,y軸的說明可能沒有了。那么重新resize的話,dpi會變成96,所以看自己吧
完整實現(xiàn)
import matplotlib.pyplot as plt # 為方便簡介為plt
import xlrd
import math
from PIL import Image
class Draw(object):
def __init__(self,file_path,pic_name=None,
legend_names=None,padx=0,pady=1,
save_path_pre="./pic"
):
"""
默認存儲的圖片為4K,600dpi
:param file_path:
:param pic_name:
:param legend_names:
:param padx:
:param pady:
:param save_path_pre:
"""
self.xl_file = xlrd.open_workbook(file_path)
self.sheet_names = self.xl_file.sheet_names()
self.legend_names = None
self.setTrans = False
self.setFig = False
self.join = False
self.padx = padx
self.pady = pady
self.save_path_pre = save_path_pre
if(pic_name):
self.pic_name = pic_name
else:
self.pic_name = self.sheet_names
if(legend_names and padx==None):
self.legend_names=legend_names
elif(legend_names==None):
sheet1 = self.xl_file.sheets()[0]
sheet1_cols = sheet1.col_values(padx)
self.legend_names = sheet1_cols[pady:]
elif(legend_names!=None):
self.legend_names = legend_names
else:
raise Exception("請檢查格式,或者參數(shù)設(shè)置")
def setTransform(self,joinPoint=None):
if(joinPoint):
self.transform = joinPoint
self.join = True
else:
self.transform_core = math.log
self.setTrans = True
def transform(self,x,pading=10000):
if(self.join):
return self.transform_core(x)
else:
return self.transform_core(x+pading)
def setFigure(self,style='seaborn-whitegrid',fig=None,
xlabel='x',ylabel='log(y)'):
self.fig = fig
self.style = style
self.xlabel = xlabel
self.ylabel = ylabel
self.setFig = True
def changeImgSiz(self,path,width=4096,height=4096):
img_switch = Image.open(path)
img_deal = img_switch.resize((width,height), Image.ANTIALIAS)
img_deal.save(path)
def creatFigure(self):
self.plt = plt
if(self.fig):
self.plt = self.fig()
else:
self.plt.rcParams['font.sans-serif'] = ['SimHei']
self.plt.rcParams['axes.unicode_minus'] = False
self.plt.figure(figsize=(8, 8))
self.plt.style.use(self.style)
self.plt.xlabel(self.xlabel)
self.plt.ylabel(self.ylabel)
return self.plt
def creatPic(self,legend_loc='upper right',multiple=40,
padding=10000,width=4096,height=3112
):
"""
:param legend_loc: 圖例的說明
:return:
"""
if(self.setFig and self.setFig):
for sheet_index in range(len(self.xl_file.sheet_names())):
sheet = self.xl_file.sheets()[sheet_index]
self.plt = self.creatFigure()
#按照行進行讀取
for row in range(self.pady,len(self.legend_names)+self.pady):
row_data_y = [self.transform(float(data),padding) for data in sheet.row_values(row)[self.padx+1:]]
row_data_x = [x*multiple for x in range(len(row_data_y))]
label_name = self.legend_names[row-self.pady]
self.plt.plot(row_data_x,row_data_y,label=label_name)
plt.legend()
save_path = self.save_path_pre+"./"+self.pic_name[sheet_index]+".jpg"
self.plt.savefig(save_path,
dpi=600, bbox_inches='tight'
)
self.changeImgSiz(save_path)
self.plt.pause(0.05)
else:
raise Exception("請先設(shè)置數(shù)據(jù)轉(zhuǎn)換方式以及繪圖")
if __name__ == '__main__':
file_path = ''
save_path_pre = ''
legend_names = ['','','']
draw = Draw(file_path,legend_names=legend_names,save_path_pre=save_path_pre)
draw.setTransform()
draw.setFigure()
draw.creatPic()
到此這篇關(guān)于python繪圖demo實現(xiàn)流程介紹的文章就介紹到這了,更多相關(guān)python繪圖內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python FastAPI 多參數(shù)傳遞的示例詳解
這篇文章主要介紹了Python FastAPI 多參數(shù)傳遞,FastAPI通過模板來匹配URL中的參數(shù)列表,大概分為三類方式傳遞參數(shù),每種方式結(jié)合示例代碼給大家介紹的非常詳細,需要的朋友可以參考下2022-12-12
Python實現(xiàn)輕松合并doc為txt的示例代碼
這篇文章主要為大家詳細介紹了如何利用Python編程語言和wxPython模塊,打開指定文件夾中的DOC文檔,并將它們的內(nèi)容合并成一個便捷的TXT文檔,需要的可以參考下2024-03-03
快速了解Python開發(fā)中的cookie及簡單代碼示例
這篇文章主要介紹了快速了解Python開發(fā)中的cookie及簡單代碼示例,具有一定借鑒價值,需要的朋友可以參考下2018-01-01
Python中使用haystack實現(xiàn)django全文檢索搜索引擎功能
django是python語言的一個web框架,功能強大。配合一些插件可為web網(wǎng)站很方便地添加搜索功能。下面通過本文給大家分享Python中使用haystack實現(xiàn)django全文檢索搜索引擎功能,感興趣的朋友一起看看吧2017-08-08

