帮我用python写一段代码 统计x和y,并用excle输出雷达图
时间: 2024-03-26 22:41:57 浏览: 74
MATLAB读写excel文件历程含,内含有测试代码
好的,以下是一段Python代码,可以统计x和y的数据,并绘制雷达图并输出到Excel中。
```python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from math import pi
from openpyxl import Workbook
from openpyxl.chart import RadarChart, Reference, Series
#定义数据
categories = ['A','B','C','D','E']
values_x = [1,2,3,4,5]
values_y = [5,4,3,2,1]
#绘制雷达图
fig = plt.figure(figsize=(6, 6))
ax = fig.add_subplot(111, polar=True)
angles = np.linspace(0, 2*pi, len(categories), endpoint=False)
angles = np.concatenate((angles, [angles[0]]))
values_x = np.concatenate((values_x, [values_x[0]]))
values_y = np.concatenate((values_y, [values_y[0]]))
ax.plot(angles, values_x, 'o-', linewidth=2, label="x")
ax.fill(angles, values_x, alpha=0.25)
ax.plot(angles, values_y, 'o-', linewidth=2, label="y")
ax.fill(angles, values_y, alpha=0.25)
ax.set_thetagrids(angles * 180/pi, categories)
ax.legend(loc='upper right', bbox_to_anchor=(0.1, 0.1))
ax.grid(True)
#输出到Excel
wb = Workbook()
ws = wb.active
for i, category in enumerate(categories):
ws.cell(row=i+1, column=1, value=category)
ws.cell(row=i+1, column=2, value=values_x[i])
ws.cell(row=i+1, column=3, value=values_y[i])
chart = RadarChart()
chart.type = "radar"
chart.style = 26
chart.title = "Radar Chart"
chart.y_axis.title = "Value"
data = Reference(ws, min_col=2, max_col=3, min_row=1, max_row=len(categories))
cats = Reference(ws, min_col=1, min_row=2, max_row=len(categories))
chart.add_data(data, titles_from_data=True)
chart.set_categories(cats)
chart.shape = 4
ws.add_chart(chart, "E2")
wb.save("radar_chart.xlsx")
```
在这段代码中,我们使用了pandas和numpy来处理数据,使用matplotlib来绘制雷达图,并使用openpyxl来将数据输出到Excel中。你只需要将你的x和y数据替换掉代码中的数据即可。
阅读全文