python批量雷達圖_python批量制作雷達圖

老板要畫雷達圖,但是數據好多組怎么辦?不能一個一個點excel去畫吧,那么可以利用python進行批量制作,得到樣式如下:

首先制作一個演示的excel,評分為excel隨機數生成:

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

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

那么接下來就是打開python寫碼了,本文是基于python3.4進行編寫

1 wb = load_workbook(filename=r'C:\Users\Administrator\Desktop\數據指標.xlsx')? ##讀取路徑

2? ? ?ws = wb.get_sheet_by_name("Sheet1")? ##讀取名字為Sheet1的sheet表

3

4? ? ?info_id = []

5? ? ?info_first = []

6

7? ? ?for row_A in range(2, 32):? ## 遍歷第2行到32行

8? ? ? ? ?id = ws.cell(row=row_A, column=1).value? ## 遍歷第2行到32行,第1列

9? ? ? ? ?info_id.append(id)

10? ? ?for col in range(2, 9):? ##讀取第1到9列

11? ? ? ? ?first = ws.cell(row=1, column=col).value

12? ? ? ? ?info_first.append(first)? ##得到1到8列的標簽

13

14? ? ?info_data = []

15? ? ?for row_num_BtoU in range(2, len(info_id) + 2):? ## 遍歷第2行到32行

16? ? ? ? ?row_empty = []? ##建立一個空數組作為臨時儲存地,每次換行就被清空

17? ? ? ? ?for i in range(2, 9):? ## 遍歷第2行到32行,第2到9列

18? ? ? ? ? ? ?data_excel = ws.cell(row=row_num_BtoU, column=i).value

19? ? ? ? ? ? ?if data_excel == None:

20? ? ? ? ? ? ? ? ?pass

21? ? ? ? ? ? ?else:

22? ? ? ? ? ? ? ? ?row_empty.append(data_excel)? ##將單元格信息儲存進去

23? ? ? ? ?info_data.append(row_empty)

分步講解:

讀取excel表格:

1   wb = load_workbook(filename=r'C:\Users\Administrator\Desktop\數據指標.xlsx')? ##讀取路徑

2? ? ?ws = wb.get_sheet_by_name("Sheet1")? ##讀取名字為Sheet1的sheet表

需要用到庫:

1 import xlsxwriter

1 from openpyxl import load_workbook

在命令指示符下輸入:

1 pip install xlsxwriter

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

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

info_id = []

info_first = []

info_data = []

讀取數據后接下來需要設置寫入的格式:

1 workbook = xlsxwriter.Workbook('C:\\Users\\Administrator\\Desktop\\result.xlsx')

2? ? ?worksheet = workbook.add_worksheet()? # 創建一個工作表對象

3? ? ?#字體格式

4? ? ?font = workbook.add_format(

5? ? ? ? ?{'border': 1, 'align': 'center', 'font_size': 11, 'font_name': '微軟雅黑'})? ##字體居中,11號,微軟雅黑,給一般的信息用的

6? ? ?#寫下第一行第一列的標簽

7? ? ?worksheet.write(0, 0, '商品貨號', font)

8? ? ?##設置圖片的那一列寬度

9? ? ?worksheet.set_column(0, len(info_first) + 1, 11)? # 設定第len(info_first) + 1列的寬度為11

將標簽數據等寫入新的excel表格中:

1 #新建一個excel保存結果

2? ? ?workbook = xlsxwriter.Workbook('C:\\Users\\Administrator\\Desktop\\result.xlsx')

3? ? ?worksheet = workbook.add_worksheet()? # 創建一個工作表對象

4? ? ?#字體格式

5? ? ?font = workbook.add_format(

6? ? ? ? ?{'border': 1, 'align': 'center', 'font_size': 11, 'font_name': '微軟雅黑'})? ##字體居中,11號,微軟雅黑,給一般的信息用的

7? ? ?#寫下第一行第一列的標簽

8? ? ?worksheet.write(0, 0, '商品貨號', font)

9? ? ?##設置圖片的那一列寬度

10? ? ?worksheet.set_column(0, len(info_first) + 1, 11)? # 設定第len(info_first) + 1列的寬度為11

11

12? ? ?##寫入標簽

13? ? ?for k in range(0,7):

14? ? ? ? ?worksheet.write(0, k + 1, info_first[k], font)

15? ? ?#寫入最后一列標簽

16? ? ?worksheet.write(0, len(info_first) + 1, '雷達圖', font)

制作雷達圖:

1? ? ?#設置雷達各個頂點的名稱

2? ? ?labels = np.array(info_first)

3? ? ?#數據個數

4? ? ?data_len = len(info_first)

5? ? ?for i in range(0,len(info_id)):

6? ? ? ? ?data = np.array(info_data[i])

7

8? ? ? ? ?angles = np.linspace(0, 2*np.pi, data_len, endpoint=False)

9? ? ? ? ?data = np.concatenate((data, [data[0]])) # 閉合

10? ? ? ? ?angles = np.concatenate((angles, [angles[0]])) # 閉合

11

12? ? ? ? ?fig = plt.figure()

13? ? ? ? ?ax = fig.add_subplot(111, polar=True)# polar參數!!

14? ? ? ? ?ax.plot(angles, data, 'bo-', linewidth=2)# 畫線

15? ? ? ? ?ax.fill(angles, data, facecolor='r', alpha=0.25)# 填充

16? ? ? ? ?ax.set_thetagrids(angles * 180/np.pi, labels, fontproperties="SimHei")

17? ? ? ? ?ax.set_title("商品貨號:" + str(info_id[i]), va='bottom', fontproperties="SimHei")

18? ? ? ? ?ax.set_rlim(3.8,5)# 設置雷達圖的范圍

19? ? ? ? ?ax.grid(True)

20? ? ? ? ?plt.savefig("C:\\Users\\Administrator\\Desktop\\result\\商品貨號:" + str(info_id[i]) + ".png", dpi=120)

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

1? ? ? ? ?import Image

2? ? ? ? ?##更改圖片大小

3? ? ? ? ?infile = “C:\\Users\\Administrator\\Desktop\\result\\商品貨號:" + str(info_id[i]) + ".png“

4? ? ? ? ?outfile = ”C:\\Users\\Administrator\\Desktop\\result1\\商品貨號:" + str(info_id[i]) + ".png”

5? ? ? ? ?im = Image.open(infile)

6? ? ? ? ?(x, y) = im.size

7? ? ? ? ?x_s = 80? ? ## 設置長

8? ? ? ? ?y_s = 100  ## 設置寬

9? ? ? ? ?out = im.resize((x_s, y_s), Image.ANTIALIAS)

10? ? ? ? ?out.save(outfile,'png',quality = 95)

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

1? ? ?if os.path.exists(r'C:\\Users\\Administrator\\Desktop\\result'):? # 建立一個文件夾在桌面,文件夾為result

2? ? ? ? ?print('result文件夾已經在桌面存在,繼續運行程序……')

3? ? ?else:

4? ? ? ? ?print('result文件夾不在桌面,新建文件夾result')

5? ? ? ? ?os.mkdir(r'C:\\Users\\Administrator\\Desktop\\result')

6? ? ? ? ?print('文件夾建立成功,繼續運行程序')

7

8? ? ?if os.path.exists(r'C:\\Users\\Administrator\\Desktop\\result1'):? # 建立一個文件夾在C盤,文件夾為result1

9? ? ? ? ?print('result1文件夾已經在桌面存在,繼續運行程序……')

10? ? ?else:

11? ? ? ? ?print('result1文件夾不在桌面,新建文件夾result1')

12? ? ? ? ?os.mkdir(r'C:\\Users\\Administrator\\Desktop\\result1')

13? ? ? ? ?print('文件夾建立成功,繼續運行程序')

最后插入圖片到excel中:

1? ? ? ? ?worksheet.insert_image(i + 1, len(info_first) + 1, 'C:\\Users\\Administrator\\Desktop\\result1\\' + "商品貨號:" + str(info_id[i]) + '.png')? ##寫入圖片

2? ? ? ? ?time.sleep(1)##防止寫入太快電腦死機

3? ? ? ? ?plt.close() #? ?一定要關掉圖片,不然python打開圖片20個后會崩潰

4

5? ? ?workbook.close()#最后關閉excel

得到的效果如下:

附上完整代碼:

1 import numpy as np

2 import matplotlib.pyplot as plt

3 import xlsxwriter

4 from openpyxl import load_workbook

5 import os

6 import time

7 from PIL import Image

8

9 if __name__ == '__main__':

10

11? ? ?if os.path.exists(r'C:\\Users\\Administrator\\Desktop\\result'):? # 建立一個文件夾在桌面,文件夾為result

12? ? ? ? ?print('result文件夾已經在桌面存在,繼續運行程序……')

13? ? ?else:

14? ? ? ? ?print('result文件夾不在桌面,新建文件夾result')

15? ? ? ? ?os.mkdir(r'C:\\Users\\Administrator\\Desktop\\result')

16? ? ? ? ?print('文件夾建立成功,繼續運行程序')

17

18? ? ?if os.path.exists(r'C:\\Users\\Administrator\\Desktop\\result1'):? # 建立一個文件夾在C盤,文件夾為result1

19? ? ? ? ?print('result1文件夾已經在桌面存在,繼續運行程序……')

20? ? ?else:

21? ? ? ? ?print('result1文件夾不在桌面,新建文件夾result1')

22? ? ? ? ?os.mkdir(r'C:\\Users\\Administrator\\Desktop\\result1')

23? ? ? ? ?print('文件夾建立成功,繼續運行程序')

24

25? ? ?wb = load_workbook(filename=r'C:\Users\Administrator\Desktop\數據指標.xlsx')? ##讀取路徑

26? ? ?ws = wb.get_sheet_by_name("Sheet1")? ##讀取名字為Sheet1的sheet表

27

28? ? ?info_id = []

29? ? ?info_first = []

30

31? ? ?for row_A in range(2, 32):? ## 遍歷第2行到32行

32? ? ? ? ?id = ws.cell(row=row_A, column=1).value? ## 遍歷第2行到32行,第1列

33? ? ? ? ?info_id.append(id)

34? ? ?for col in range(2, 9):? ##讀取第1到9列

35? ? ? ? ?first = ws.cell(row=1, column=col).value

36? ? ? ? ?info_first.append(first)? ##得到1到8列的標簽

37? ? ?print(info_id)

38? ? ?print(info_first)

39

40? ? ?info_data = []

41? ? ?for row_num_BtoU in range(2, len(info_id) + 2):? ## 遍歷第2行到32行

42? ? ? ? ?row_empty = []? ##建立一個空數組作為臨時儲存地,每次換行就被清空

43? ? ? ? ?for i in range(2, 9):? ## 遍歷第2行到32行,第2到9列

44? ? ? ? ? ? ?data_excel = ws.cell(row=row_num_BtoU, column=i).value

45? ? ? ? ? ? ?if data_excel == None:

46? ? ? ? ? ? ? ? ?pass

47? ? ? ? ? ? ?else:

48? ? ? ? ? ? ? ? ?row_empty.append(data_excel)? ##將單元格信息儲存進去

49? ? ? ? ?info_data.append(row_empty)

50? ? ?print(info_data)

51? ? ?print(len(info_data))

52

53? ? ?# 設置雷達各個頂點的名稱

54? ? ?labels = np.array(info_first)

55? ? ?# 數據個數

56? ? ?data_len = len(info_first)

57? ? ?# 新建一個excel保存結果

58? ? ?workbook = xlsxwriter.Workbook('C:\\Users\\Administrator\\Desktop\\result.xlsx')

59? ? ?worksheet = workbook.add_worksheet()? # 創建一個工作表對象

60? ? ?# 字體格式

61? ? ?font = workbook.add_format(

62? ? ? ? ?{'border': 1, 'align': 'center', 'font_size': 11, 'font_name': '微軟雅黑'})? ##字體居中,11號,微軟雅黑,給一般的信息用的

63? ? ?# 寫下第一行第一列的標簽

64? ? ?worksheet.write(0, 0, '商品貨號', font)

65? ? ?##設置圖片的那一列寬度

66? ? ?worksheet.set_column(0, len(info_first) + 1, 11)? # 設定第len(info_first) + 1列的寬度為11

67

68? ? ?##寫入標簽

69? ? ?for k in range(0, 7):

70? ? ? ? ?worksheet.write(0, k + 1, info_first[k], font)

71? ? ?# 寫入最后一列標簽

72? ? ?worksheet.write(0, len(info_first) + 1, '雷達圖', font)

73

74? ? ?# 將其他參數寫入excel中

75? ? ?for j in range(0, len(info_id)):

76? ? ? ? ?worksheet.write(j + 1, 0, info_id[j], font)? # 寫入商品貨號

77? ? ? ? ?worksheet.set_row(j, 76)? ##設置行寬

78? ? ? ? ?for x in range(0, len(info_first)):

79? ? ? ? ? ? ?worksheet.write(j + 1, x + 1, info_data[j][x], font)? # 寫入商品的其他參數

80

81? ? ?for i in range(0, len(info_id)):

82? ? ? ? ?data = np.array(info_data[i])

83

84? ? ? ? ?angles = np.linspace(0, 2 * np.pi, data_len, endpoint=False)

85? ? ? ? ?data = np.concatenate((data, [data[0]]))? # 閉合

86? ? ? ? ?angles = np.concatenate((angles, [angles[0]]))? # 閉合

87

88? ? ? ? ?fig = plt.figure()

89? ? ? ? ?ax = fig.add_subplot(111, polar=True)? # polar參數!!

90? ? ? ? ?ax.plot(angles, data, 'bo-', linewidth=2)? # 畫線

91? ? ? ? ?ax.fill(angles, data, facecolor='r', alpha=0.25)? # 填充

92? ? ? ? ?ax.set_thetagrids(angles * 180 / np.pi, labels, fontproperties="SimHei")

93? ? ? ? ?ax.set_title("商品貨號:" + str(info_id[i]), va='bottom', fontproperties="SimHei")

94? ? ? ? ?ax.set_rlim(3.8, 5)? # 設置雷達圖的范圍

95? ? ? ? ?ax.grid(True)

96? ? ? ? ?plt.savefig("C:\\Users\\Administrator\\Desktop\\result\\商品貨號:" + str(info_id[i]) + ".png", dpi=120)

97? ? ? ? ?# plt.show()在python中顯示

98

99? ? ? ? ?##更改圖片大小

100? ? ? ? ?infile = "C:\\Users\\Administrator\\Desktop\\result\\商品貨號:" + str(info_id[i]) + ".png"

101? ? ? ? ?outfile = "C:\\Users\\Administrator\\Desktop\\result1\\商品貨號:" + str(info_id[i]) + ".png"

102? ? ? ? ?im = Image.open(infile)

103? ? ? ? ?(x, y) = im.size

104? ? ? ? ?x_s = 80? ## 設置長

105? ? ? ? ?y_s = 100? ## 設置寬

106? ? ? ? ?out = im.resize((x_s, y_s), Image.ANTIALIAS)

107? ? ? ? ?out.save(outfile, 'png', quality=95)

108

109? ? ? ? ?worksheet.insert_image(i + 1, len(info_first) + 1,

110? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 'C:\\Users\\Administrator\\Desktop\\result1\\' + "商品貨號:" + str(

111? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? info_id[i]) + '.png')? ##寫入圖片

112? ? ? ? ?time.sleep(1)? ##防止寫入太快電腦死機

113? ? ? ? ?plt.close()? # 一定要關掉圖片,不然python打開圖片20個后會崩潰

114

115? ? ?workbook.close()? # 最后關閉excel

轉載于:https://www.cnblogs.com/TTyb/p/5703106.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/541907.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/541907.shtml
英文地址,請注明出處:http://en.pswp.cn/news/541907.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

JavaScript中帶有示例的Math.log()方法

JavaScript | Math.log()方法 (JavaScript | Math.log() Method) Math.log() is a function in math library of JavaScript that is used to return the value of natural Log i.e. (base e) of the given number. It is also known as ln(x) in mathematical terms. Math.log…

SUI踩坑記錄

SUI踩坑記錄 最近做了個項目選型了SUI和vue做單頁應用。下面記錄一下踩坑經歷SUI 介紹 sui文檔:http://m.sui.taobao.org/SUI Mobile 是一套基于 Framework7 開發的UI庫。它非常輕量、精美,只需要引入我們的CDN文件就可以使用,并且能兼容到 i…

java 寫入xml文件_java讀寫xml文件

要讀的xml文件李華姓名>14年齡>學生>張三姓名>16年齡>學生>學生花名冊>package xml;import java.io.FileOutputStream;import java.io.OutputStreamWriter;import java.io.Writer;import java.util.Iterator;import java.util.Vector;import javax.xml.pa…

JavaScript中帶有示例的Math.max()方法

JavaScript | Math.max()方法 (JavaScript | Math.max() Method) Math.max() is a function in math library of JavaScript that is used to return the greatest value of all the passed values to the method. Math.max()是JavaScript數學庫中的函數,用于將所有…

java 修飾符默認_Java和C#默認訪問修飾符

C#中:針對下面幾種類型內部成員的訪問修飾符:enum的默認訪問修飾符:public。class的默認為private。interface默認為public。struct默認為private。其中:public可以被任意存取;protected只可以被本類和其繼承子類存取&…

JavaScript中帶有示例的Math.abs()方法

JavaScript | Math.abs()方法 (JavaScript | Math.abs() Method) Math operations in JavaScript are handled using functions of math library in JavaScript. In this tutorial on Math.abs() method, we will learn about the abs() method and its working with examples.…

人臉識別python face_recognize_python2.7使用face_recognition做人臉識別

偶然看到一篇文章,說是可以實時人臉識別,很有興趣就自己按照文章開始動手人臉識別,但是實現過程中遇到了幾個問題這里做個總結,希望可以幫助到大家安裝face_recognition這個之前需要先安裝編譯dlib,如果沒有安裝dlib&a…

c# reverse_清單 .Reverse()方法,以C#為例

c# reverseC&#xff03;List <T> .Reverse()方法 (C# List<T>.Reverse() Method) List<T>.Reverse() method is used to reverse the all list elements. List <T> .Reverse()方法用于反轉所有列表元素。 Syntax: 句法&#xff1a; void List<T&…

cpuinfo詳解

cat /proc/cpuinfo processor: 23&#xff1a;超線程技術的虛擬邏輯核第24個 ###一般看最后一個0...23 表示24線程 vendor_id: GenuineIntel&#xff1a;CPU制造商cpu family: 6&#xff1a;CPU產品系列代號model: 44&#xff1a;CPU屬于其系列中的哪一代號model name: Intel…

jvm延遲偏向_用于偏向硬幣翻轉模擬的Python程序

jvm延遲偏向Here, we will be simulating the occurrence coin face i.e. H - HEAD, T - TAIL. Simply we are going to use an inbuilt library called as random to call a random value from given set and thereby we can stimulate the occurrence value by storing the o…

java項目沒有bin_WebAPI項目似乎沒有將轉換后的web.config發布到bin文件夾?

我很擅長.NET配置轉換 . 我現在將它們放在用于數據使用的類庫和WPF應用程序上 .但是&#xff0c;當我嘗試使用ASP.NET WebAPI項目進行設置時&#xff0c;似乎發生了一些奇怪的事情 .配置文件永遠不會顯示在我的bin目錄中&#xff0c;因此web.config始終顯示為預先形成的配置文件…

opengl es的射線拾取

2019獨角獸企業重金招聘Python工程師標準>>> 在opengl中關于拾取有封裝好的選擇模式&#xff0c;名字棧&#xff0c;命中記錄&#xff0c;實現拾取的功能&#xff0c;相對容易一些。但是到了opengl es里面就比較倒霉了&#xff0c;因為opengl es是opengl的簡化版&am…

java timezone_Java TimeZone useDaylightTime()方法與示例

java timezoneTimeZone類useDaylightTime()方法 (TimeZone Class useDaylightTime() method) useDaylightTime() method is available in java.util package. useDaylightTime()方法在java.util包中可用。 useDaylightTime() method is used to check whether this time zone u…

視覺學習(4) —— 添加地址傳遞數據

Modbus Slave 選擇一個地址右鍵&#xff0c;選擇發送的數據類型 視覺軟件 一、添加地址 當地址為100時&#xff0c;先將首地址改為100&#xff0c;第0個地址為100&#xff0c;第1個地址為101&#xff0c;往后累加 若想使用100—150的地址&#xff0c;即首地址為100&#xff…

某個JAVA類斷點無效_解決eclipse中斷點調試不起作用的問題

最近幾天&#xff0c;遇到了一個問題&#xff0c;就是在eclipse中進行斷點調試程序到時候&#xff0c;跟蹤不到我設置的斷點。困惑了很久&#xff0c;在網上也查閱了很多資料&#xff0c;都沒能解決我的問題。今天早上&#xff0c;我試著把eclipse的工作空間重新換了一個&#…

jquery中阻止事件冒泡的方法

2019獨角獸企業重金招聘Python工程師標準>>> 根據《jquery基礎教程》 第一種方法&#xff1a;判斷事件的“直接”目標是否是自身&#xff0c;如果不是自身&#xff0c;不予處理 $(div.outter).click(function(event) {if (event.target this) {$(p).css(color, red…

java swing 組織機構_課內資源 - 基于Java Swing的小型社團成員管理系統

一、需求分析1.1 個人信息學號、姓名、性別、年級、系別、專業、出生日期、聯系方式、個性簽名、地址、照片。1.2 基本功能要求管理員信息管理登錄、注銷功能修改密碼功能部落成員信息管理添加成員刪除成員修改成員信息按條件查找篩選成員1.3 高級特性管理員權限管理成員信息包…

Java System類loadLibrary()方法與示例

系統類loadLibrary()方法 (System class loadLibrary() method) loadLibrary() method is available in java.lang package. loadLibrary()方法在java.lang包中可用。 loadLibrary() method is used to load the library with the given parameter named library_name(library …

CCF201509-2 日期計算(100分)

試題編號&#xff1a; 201509-2 試題名稱&#xff1a; 日期計算 時間限制&#xff1a; 1.0s 內存限制&#xff1a; 256.0MB 問題描述&#xff1a; 問題描述給定一個年份y和一個整數d&#xff0c;問這一年的第d天是幾月幾日&#xff1f;注意閏年的2月有29天。滿足下面條件之一的…