
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的大家有所幫助
數據分析咨詢請掃描二維碼
若不方便掃碼,搜微信號:CDAshujufenxi
CDA數據分析師證書考試體系(更新于2025年05月22日)
2025-05-26解碼數據基因:從數字敏感度到邏輯思維 每當看到超市貨架上商品的排列變化,你是否會聯想到背后的銷售數據波動?三年前在零售行 ...
2025-05-23在本文中,我們將探討 AI 為何能夠加速數據分析、如何在每個步驟中實現數據分析自動化以及使用哪些工具。 數據分析中的AI是什么 ...
2025-05-20當數據遇見人生:我的第一個分析項目 記得三年前接手第一個數據分析項目時,我面對Excel里密密麻麻的銷售數據手足無措。那些跳動 ...
2025-05-20在數字化運營的時代,企業每天都在產生海量數據:用戶點擊行為、商品銷售記錄、廣告投放反饋…… 這些數據就像散落的拼圖,而相 ...
2025-05-19在當今數字化營銷時代,小紅書作為國內領先的社交電商平臺,其銷售數據蘊含著巨大的商業價值。通過對小紅書銷售數據的深入分析, ...
2025-05-16Excel作為最常用的數據分析工具,有沒有什么工具可以幫助我們快速地使用excel表格,只要輕松幾步甚至輸入幾項指令就能搞定呢? ...
2025-05-15數據,如同無形的燃料,驅動著現代社會的運轉。從全球互聯網用戶每天產生的2.5億TB數據,到制造業的傳感器、金融交易 ...
2025-05-15大數據是什么_數據分析師培訓 其實,現在的大數據指的并不僅僅是海量數據,更準確而言是對大數據分析的方法。傳統的數 ...
2025-05-14CDA持證人簡介: 萬木,CDA L1持證人,某電商中廠BI工程師 ,5年數據經驗1年BI內訓師,高級數據分析師,擁有豐富的行業經驗。 ...
2025-05-13CDA持證人簡介: 王明月 ,CDA 數據分析師二級持證人,2年數據產品工作經驗,管理學博士在讀。 學習入口:https://edu.cda.cn/g ...
2025-05-12CDA持證人簡介: 楊貞璽 ,CDA一級持證人,鄭州大學情報學碩士研究生,某上市公司數據分析師。 學習入口:https://edu.cda.cn/g ...
2025-05-09CDA持證人簡介 程靖 CDA會員大咖,暢銷書《小白學產品》作者,13年頂級互聯網公司產品經理相關經驗,曾在百度、美團、阿里等 ...
2025-05-07相信很多做數據分析的小伙伴,都接到過一些高階的數據分析需求,實現的過程需要用到一些數據獲取,數據清洗轉換,建模方法等,這 ...
2025-05-06以下的文章內容來源于劉靜老師的專欄,如果您想閱讀專欄《10大業務分析模型突破業務瓶頸》,點擊下方鏈接 https://edu.cda.cn/g ...
2025-04-30CDA持證人簡介: 邱立峰 CDA 數據分析師二級持證人,數字化轉型專家,數據治理專家,高級數據分析師,擁有豐富的行業經驗。 ...
2025-04-29CDA持證人簡介: 程靖 CDA會員大咖,暢銷書《小白學產品》作者,13年頂級互聯網公司產品經理相關經驗,曾在百度,美團,阿里等 ...
2025-04-28CDA持證人簡介: 居瑜 ,CDA一級持證人國企財務經理,13年財務管理運營經驗,在數據分析就業和實踐經驗方面有著豐富的積累和經 ...
2025-04-27數據分析在當今信息時代發揮著重要作用。單因素方差分析(One-Way ANOVA)是一種關鍵的統計方法,用于比較三個或更多獨立樣本組 ...
2025-04-25CDA持證人簡介: 居瑜 ,CDA一級持證人國企財務經理,13年財務管理運營經驗,在數據分析就業和實踐經驗方面有著豐富的積累和經 ...
2025-04-25