Как я могу превратить свой DataFrame в радиолокационную диаграмму, используя Python? - PullRequest
0 голосов
/ 14 февраля 2020

У меня есть DataFrame, который я хочу превратить в радарную диаграмму. DataFrame выглядит так, когда он запускается ...

╔═══════════════════╗
║ Col A      Col B  ║
╠═══════════════════╣
║ Home       6.797  ║
║ Other      3.243  ║
║ Used       12.567 ║
║ New        8.985  ║
║ Service    1.345  ║
╚═══════════════════╝

Я изменил код, который нашел в другом вопросе переполнения стека, касающемся Pandas и радарных диаграмм, и он работает по большей части, за исключением того, что я могу ' t получить значения 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()

И диаграмма выглядит следующим образом ...

enter image description here

Так как я все еще такой новичок ie в Python, я понятия не имею, что я делаю здесь неправильно. Я перепробовал много вещей, чтобы изменить код, включая удаление первых двух строк кода и просто вместо этого ... points = df['Col B'], но все, что он делал, это стирал имена по кругу, оставляя все остальное таким же. Что я здесь не так делаю?

Кроме того, как я могу заполнить область внутри тета светло-зеленым? Я попытался 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', и я не могу решить эту проблему.

Любая помощь очень ценится!

1 Ответ

2 голосов
/ 14 февраля 2020

Ниже приведена адаптация кода на в этом примере , чтобы вы могли начать с того, как хранятся ваши данные.

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

resulting radar plot

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...