python - 如何使用 Python 将我的 DataFrame 转换为雷达图?
问题描述
我有一个要变成雷达图的 DataFrame。DataFrame 运行时看起来像这样...
╔═══════════════════╗
║ Col A Col B ║
╠═══════════════════╣
║ Home 6.797 ║
║ Other 3.243 ║
║ Used 12.567 ║
║ New 8.985 ║
║ Service 1.345 ║
╚═══════════════════╝
我重新利用了在另一个与 Pandas 和 Radar Charts 有关的 Stack Overflow 问题上找到的一些代码,它在大多数情况下都有效,除了我无法让 Col B 的值在图表中正确对齐。下面是我正在使用的代码...
df['Z'] = np.ones(len(df))
points = mergedFrame.pivot_table(values='Z', index=['Col A'], columns=['Col B'])
fig = plt.figure()
ax = fig.add_subplot(111, projection="polar")
theta = np.arange(len(points))/float(len(points))*2.*np.pi
l1, = ax.plot(theta, color="C2", marker="o", label="Name of Col B")
def _closeline(line):
x, y = line.get_data()
x = np.concatenate((x, [x[0]]))
y = np.concatenate((y, [y[0]]))
line.set_data(x, y)
[_closeline(l) for l in [l1]]
ax.set_xticks(radar)
ax.set_xticklabels(points.index)
plt.legend()
plt.title("Title")
plt.show()
图表看起来像这样......
由于我仍然是 Python 的新手,我不知道我在这里做错了什么。我已经尝试了很多方法来修改代码,包括删除前两行代码并简单地放置......points = df['Col B']
但它所做的只是擦除圆圈周围的名称,同时保持其他所有内容相同。我在这里做错了什么?
另外,如何用浅绿色填充 theta 内部的区域?l1, = ax.fill(theta, facecolor = 'g', alpha=0.25)
我在该行下方尝试过l1, = ax.plot(theta, color="C2", marker="o", label="Name of Col B")
,但它给了我这个错误AttributeError: 'Polygon' object has no attribute 'get_data'
,我似乎无法解决。
任何帮助深表感谢!
解决方案
这是此示例中代码的改编,可帮助您开始了解数据的存储方式。
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
df = pd.DataFrame({'Col A': ['home', 'other', 'used', 'new', 'service'],
'Col B': [6.797, 3.243, 12.567, 8.985, 1.345]})
fig = plt.figure()
ax = fig.add_subplot(111, projection="polar")
# theta has 5 different angles, and the first one repeated
theta = np.arange(len(df) + 1) / float(len(df)) * 2 * np.pi
# values has the 5 values from 'Col B', with the first element repeated
values = df['Col B'].values
values = np.append(values, values[0])
# draw the polygon and the mark the points for each angle/value combination
l1, = ax.plot(theta, values, color="C2", marker="o", label="Name of Col B")
plt.xticks(theta[:-1], df['Col A'], color='grey', size=12)
ax.tick_params(pad=10) # to increase the distance of the labels to the plot
# fill the area of the polygon with green and some transparency
ax.fill(theta, values, 'green', alpha=0.1)
# plt.legend() # shows the legend, using the label of the line plot (useful when there is more than 1 polygon)
plt.title("Title")
plt.show()
推荐阅读
- asp.net-mvc - System.Web.dll 中出现“System.InsufficientExecutionStackException”类型的异常,但在 nopcommerce 3.80 的用户代码中未处理
- java - 使用 Java 8 流对象将列表对象转换为自定义 Map
- avro - AvroData 用架构默认值替换空值
- javascript - 立即停止 Puppeteer 删除文本
- javascript - 使用自动 ID 增量将数据保存在数组中
- reactjs - 从 React 访问输入元素的电子邮件伪类?
- php - 如何使用 wordpress 功能调整图像大小
- python - 我的 'if int(time.time()) % 2 == 0:' 并不总是打印出甚至秒
- php - 使用ajax问题进行实时表编辑和更新
- javascript - 如果不存在则创建新的,否则在firebase中更新