python批量製作雷達圖的實現方法,python雷達圖

來源:互聯網
上載者:User

python批量製作雷達圖的實現方法,python雷達圖

前言

因為工作需要有時候要畫雷達圖,但是資料好多組怎麼辦?不能一個一個點excel去畫吧,那麼可以利用python進行批量製作,得到樣式如下:

首先製作一個示範的excel,評分為excel隨機數產生:

1 =INT((RAND()+4)*10)/10 

加入標籤等得到的excel樣式如下(部分,共計32行):

那麼接下來就是開啟python寫碼了,本文是基於pycharm進行編寫

 

 wb = load_workbook(filename=r'C:\Users\Administrator\Desktop\資料指標.xlsx') ##讀取路徑   ws = wb.get_sheet_by_name("Sheet1") ##讀取名字為Sheet1的sheet表    info_id = []   info_first = []    for row_A in range(2, 32): ## 遍曆第2行到32行     id = ws.cell(row=row_A, column=1).value ## 遍曆第2行到32行,第1列     info_id.append(id)   for col in range(2, 9): ##讀取第1到9列     first = ws.cell(row=1, column=col).value     info_first.append(first) ##得到1到8列的標籤    info_data = []   for row_num_BtoU in range(2, len(info_id) + 2): ## 遍曆第2行到32行     row_empty = [] ##建立一個空數組作為臨時儲存地,每次換行就被清空     for i in range(2, 9): ## 遍曆第2行到32行,第2到9列       data_excel = ws.cell(row=row_num_BtoU, column=i).value       if data_excel == None:         pass       else:         row_empty.append(data_excel) ##將儲存格資訊儲存進去     info_data.append(row_empty)

分步講解:

讀取excel表格:

   wb = load_workbook(filename=r'C:\Users\Administrator\Desktop\資料指標.xlsx') ##讀取路徑   ws = wb.get_sheet_by_name("Sheet1") ##讀取名字為Sheet1的sheet表


需要用到庫:

 import xlsxwriter

 from openpyxl import load_workbook

在命令指示符下輸入:

 pip install xlsxwriter

等待安裝即可,後面的庫也是如此:

將第一列ID儲存,以及第一行的標籤,標籤下面的數值分別儲存在:

  info_id = []  info_first = []  info_data = []

讀取資料後接下來需要設定寫入的格式:

 workbook = xlsxwriter.Workbook('C:\\Users\\Administrator\\Desktop\\result.xlsx')   worksheet = workbook.add_worksheet() # 建立一個工作表對象   #字型格式   font = workbook.add_format(     {'border': 1, 'align': 'center', 'font_size': 11, 'font_name': '微軟雅黑'}) ##字型置中,11號,微軟雅黑,給一般的資訊用的   #寫下第一行第一列的標籤   worksheet.write(0, 0, '商品貨號', font)   ##設定圖片的那一列寬度   worksheet.set_column(0, len(info_first) + 1, 11) # 設定第len(info_first) + 1列的寬度為11

將標籤資料等寫入新的excel表格中:

#建立一個excel儲存結果   workbook = xlsxwriter.Workbook('C:\\Users\\Administrator\\Desktop\\result.xlsx')   worksheet = workbook.add_worksheet() # 建立一個工作表對象   #字型格式   font = workbook.add_format(     {'border': 1, 'align': 'center', 'font_size': 11, 'font_name': '微軟雅黑'}) ##字型置中,11號,微軟雅黑,給一般的資訊用的   #寫下第一行第一列的標籤   worksheet.write(0, 0, '商品貨號', font)   ##設定圖片的那一列寬度   worksheet.set_column(0, len(info_first) + 1, 11) # 設定第len(info_first) + 1列的寬度為11    ##寫入標籤   for k in range(0,7):     worksheet.write(0, k + 1, info_first[k], font)   #寫入最後一欄標籤   worksheet.write(0, len(info_first) + 1, '雷達圖', font)

製作雷達圖:

   #設定雷達各個頂點的名稱   labels = np.array(info_first)   #資料個數   data_len = len(info_first)   for i in range(0,len(info_id)):     data = np.array(info_data[i])      angles = np.linspace(0, 2*np.pi, data_len, endpoint=False)     data = np.concatenate((data, [data[0]])) # 閉合     angles = np.concatenate((angles, [angles[0]])) # 閉合      fig = plt.figure()     ax = fig.add_subplot(111, polar=True)# polar參數!!     ax.plot(angles, data, 'bo-', linewidth=2)# 畫線     ax.fill(angles, data, facecolor='r', alpha=0.25)# 填充     ax.set_thetagrids(angles * 180/np.pi, labels, fontproperties="SimHei")     ax.set_title("商品貨號:" + str(info_id[i]), va='bottom', fontproperties="SimHei")     ax.set_rlim(3.8,5)# 設定雷達圖的範圍     ax.grid(True)     plt.savefig("C:\\Users\\Administrator\\Desktop\\result\\商品貨號:" + str(info_id[i]) + ".png", dpi=120)

圖片太大怎麼辦?用庫改變大小即可

     import Image     ##更改圖片大小     infile = “C:\\Users\\Administrator\\Desktop\\result\\商品貨號:" + str(info_id[i]) + ".png“     outfile = ”C:\\Users\\Administrator\\Desktop\\result1\\商品貨號:" + str(info_id[i]) + ".png”     im = Image.open(infile)     (x, y) = im.size     x_s = 80  ## 設定長     y_s = 100  ## 設定寬     out = im.resize((x_s, y_s), Image.ANTIALIAS)     out.save(outfile,'png',quality = 95)

將大圖片和小圖片放在了result和result1兩個不同的檔案夾,需要再前邊建立這兩個檔案夾:

   if os.path.exists(r'C:\\Users\\Administrator\\Desktop\\result'): # 建立一個檔案夾在案頭,檔案夾為result     print('result檔案夾已經在案頭存在,繼續運行程式……')   else:     print('result檔案夾不在案頭,建立檔案夾result')     os.mkdir(r'C:\\Users\\Administrator\\Desktop\\result')     print('檔案夾建立成功,繼續運行程式')    if os.path.exists(r'C:\\Users\\Administrator\\Desktop\\result1'): # 建立一個檔案夾在C盤,檔案夾為result1     print('result1檔案夾已經在案頭存在,繼續運行程式……')   else:     print('result1檔案夾不在案頭,建立檔案夾result1')     os.mkdir(r'C:\\Users\\Administrator\\Desktop\\result1')     print('檔案夾建立成功,繼續運行程式')

最後插入圖片到excel中:

     worksheet.insert_image(i + 1, len(info_first) + 1, 'C:\\Users\\Administrator\\Desktop\\result1\\' + "商品貨號:" + str(info_id[i]) + '.png') ##寫入圖片     time.sleep(1)##防止寫入太快電腦死機     plt.close() #  一定要關掉圖片,不然python開啟圖片20個後會崩潰    workbook.close()#最後關閉excel

得到的效果如下:

附上完整代碼:

  import numpy as np  import matplotlib.pyplot as plt  import xlsxwriter  from openpyxl import load_workbook  import os  import time  from PIL import Image    if __name__ == '__main__':    if os.path.exists(r'C:\\Users\\Administrator\\Desktop\\result'): # 建立一個檔案夾在案頭,檔案夾為result     print('result檔案夾已經在案頭存在,繼續運行程式……')   else:     print('result檔案夾不在案頭,建立檔案夾result')     os.mkdir(r'C:\\Users\\Administrator\\Desktop\\result')     print('檔案夾建立成功,繼續運行程式')    if os.path.exists(r'C:\\Users\\Administrator\\Desktop\\result1'): # 建立一個檔案夾在C盤,檔案夾為result1     print('result1檔案夾已經在案頭存在,繼續運行程式……')   else:     print('result1檔案夾不在案頭,建立檔案夾result1')     os.mkdir(r'C:\\Users\\Administrator\\Desktop\\result1')     print('檔案夾建立成功,繼續運行程式')    wb = load_workbook(filename=r'C:\Users\Administrator\Desktop\資料指標.xlsx') ##讀取路徑   ws = wb.get_sheet_by_name("Sheet1") ##讀取名字為Sheet1的sheet表    info_id = []   info_first = []    for row_A in range(2, 32): ## 遍曆第2行到32行     id = ws.cell(row=row_A, column=1).value ## 遍曆第2行到32行,第1列     info_id.append(id)   for col in range(2, 9): ##讀取第1到9列     first = ws.cell(row=1, column=col).value     info_first.append(first) ##得到1到8列的標籤   print(info_id)   print(info_first)    info_data = []   for row_num_BtoU in range(2, len(info_id) + 2): ## 遍曆第2行到32行     row_empty = [] ##建立一個空數組作為臨時儲存地,每次換行就被清空     for i in range(2, 9): ## 遍曆第2行到32行,第2到9列       data_excel = ws.cell(row=row_num_BtoU, column=i).value       if data_excel == None:         pass       else:         row_empty.append(data_excel) ##將儲存格資訊儲存進去     info_data.append(row_empty)   print(info_data)   print(len(info_data))    # 設定雷達各個頂點的名稱   labels = np.array(info_first)   # 資料個數   data_len = len(info_first)   # 建立一個excel儲存結果   workbook = xlsxwriter.Workbook('C:\\Users\\Administrator\\Desktop\\result.xlsx')   worksheet = workbook.add_worksheet() # 建立一個工作表對象   # 字型格式   font = workbook.add_format(     {'border': 1, 'align': 'center', 'font_size': 11, 'font_name': '微軟雅黑'}) ##字型置中,11號,微軟雅黑,給一般的資訊用的   # 寫下第一行第一列的標籤   worksheet.write(0, 0, '商品貨號', font)   ##設定圖片的那一列寬度   worksheet.set_column(0, len(info_first) + 1, 11) # 設定第len(info_first) + 1列的寬度為11    ##寫入標籤   for k in range(0, 7):     worksheet.write(0, k + 1, info_first[k], font)   # 寫入最後一欄標籤   worksheet.write(0, len(info_first) + 1, '雷達圖', font)    # 將其他參數寫入excel中   for j in range(0, len(info_id)):     worksheet.write(j + 1, 0, info_id[j], font) # 寫入商品貨號     worksheet.set_row(j, 76) ##設定行寬     for x in range(0, len(info_first)):       worksheet.write(j + 1, x + 1, info_data[j][x], font) # 寫入商品的其他參數    for i in range(0, len(info_id)):     data = np.array(info_data[i])      angles = np.linspace(0, 2 * np.pi, data_len, endpoint=False)     data = np.concatenate((data, [data[0]])) # 閉合     angles = np.concatenate((angles, [angles[0]])) # 閉合      fig = plt.figure()     ax = fig.add_subplot(111, polar=True) # polar參數!!     ax.plot(angles, data, 'bo-', linewidth=2) # 畫線     ax.fill(angles, data, facecolor='r', alpha=0.25) # 填充     ax.set_thetagrids(angles * 180 / np.pi, labels, fontproperties="SimHei")     ax.set_title("商品貨號:" + str(info_id[i]), va='bottom', fontproperties="SimHei")     ax.set_rlim(3.8, 5) # 設定雷達圖的範圍     ax.grid(True)     plt.savefig("C:\\Users\\Administrator\\Desktop\\result\\商品貨號:" + str(info_id[i]) + ".png", dpi=120)     # plt.show()在python中顯示      ##更改圖片大小     infile = "C:\\Users\\Administrator\\Desktop\\result\\商品貨號:" + str(info_id[i]) + ".png"     outfile = "C:\\Users\\Administrator\\Desktop\\result1\\商品貨號:" + str(info_id[i]) + ".png"     im = Image.open(infile)     (x, y) = im.size     x_s = 80 ## 設定長     y_s = 100 ## 設定寬     out = im.resize((x_s, y_s), Image.ANTIALIAS)     out.save(outfile, 'png', quality=95)      worksheet.insert_image(i + 1, len(info_first) + 1,                'C:\\Users\\Administrator\\Desktop\\result1\\' + "商品貨號:" + str(                  info_id[i]) + '.png') ##寫入圖片     time.sleep(1) ##防止寫入太快電腦死機     plt.close() # 一定要關掉圖片,不然python開啟圖片20個後會崩潰    workbook.close() # 最後關閉excel

以上就是本文介紹利用python批量製作雷達圖的實現方法,希望給學習python的大家有所協助

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.