資訊內容
一分鐘學會用Python的第三方庫openpyxl畫真散點圖
uwA少兒編程網-https://www.pxcodes.com
之前在博客上看見不少類似的問題,點進去一看,發現都是完全照抄的*方文檔。然而*方文檔的demo,畫出來并不是我們想要的效果:uwA少兒編程網-https://www.pxcodes.com
說好的散點圖,出來卻是我們一般定義上的折線圖。
uwA少兒編程網-https://www.pxcodes.com
直接上代碼:uwA少兒編程網-https://www.pxcodes.com
先安裝openpyxl第三方庫,以Windows為例,在cmd指令窗下發如下命令:uwA少兒編程網-https://www.pxcodes.com
pip install openpyxlPython代碼如下:uwA少兒編程網-https://www.pxcodes.com
""" __author__ = '伴月雎' __time__ = '2021/4/21 19:15' """ from openpyxl import Workbook from openpyxl.chart import ( ScatterChart, Reference, Series, ) wb = Workbook() ws = wb.active rows = [ ['Size', 'Batch 1', 'Batch 2'], [2, 40, 30], [3, 40, 25], [4, 50, 30], [5, 30, 25], [6, 25, 35], [7, 20, 40], ] for row in rows: ws.append(row) chart = ScatterChart() chart.title = "Scatter Chart" chart.style = 10 chart.x_axis.title = 'Size' chart.y_axis.title = 'Percentage' xvalues = Reference(ws, min_col=1, min_row=2, max_row=7) for i in range(2, 4): values = Reference(ws, min_col=i, min_row=1, max_row=7) series = Series(values, xvalues, title_from_data=True) chart.series.append(series) # 第一條散點 s1 = chart.series[0] # 散點標記類型 'auto', 'dash', 'triangle', 'square', 'picture', 'circle', 'dot', 'plus', 'star', 'diamond', 'x' s1.marker.symbol = "circle" s1.marker.graphicalProperties.solidFill = "0000FF" # Marker filling 設定標記填充的顏色 s1.marker.graphicalProperties.line.solidFill = "0000FF" # Marker outline 標記輪廓的顏色 s1.graphicalProperties.line.noFill = True # 關閉連線填充 # 第二條帶連線的散點 s2 = chart.series[1] s2.marker.symbol = "circle" s2.graphicalProperties.solidFill = "FF0000" s2.marker.graphicalProperties.line.solidFill = "FF0000" s2.graphicalProperties.dashStyle = "dash" s2.graphicalProperties.line.width = 1000 # width in EMUs ws.add_chart(chart, "A10") wb.save("scatter.xlsx")效果如下:uwA少兒編程網-https://www.pxcodes.com
uwA少兒編程網-https://www.pxcodes.com
大家可以根據自己的需要做相應的擴展:uwA少兒編程網-https://www.pxcodes.com
1.讀取自己的Excel表格數據,替換上面代碼中手動生成的數據:uwA少兒編程網-https://www.pxcodes.com
wb = openpyxl.load_workbook('D:\data.xlsx') # 填寫你的Excel文件路徑 ws = workbook['sheet1'] # 填寫你的sheet標題再參考上述代碼,指定你的xvalues和values(即x軸,y軸)對應的行、列位就OK了。uwA少兒編程網-https://www.pxcodes.com
2.**后修改畫圖元素的屬性值,畫出你自己定制化的散點圖!uwA少兒編程網-https://www.pxcodes.com
相關免費學習推薦:python視頻教程!
以上就是一分鐘學會用Python的第三方庫openpyxl畫真散點圖的詳細內容,更多請關注少兒編程網其它相關文章!uwA少兒編程網-https://www.pxcodes.com
