首页 > 解决方案 > 如何使用 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',我似乎无法解决。

任何帮助深表感谢!

标签: pythonpandasmatplotlib

解决方案


这是此示例中代码的改编,可帮助您开始了解数据的存储方式。

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()

结果雷达图


推荐阅读