Python 3.x 使雷达条形图列跨越整个条形图宽度-Matplotlib

Python 3.x 使雷达条形图列跨越整个条形图宽度-Matplotlib,python-3.x,matplotlib,radar-chart,Python 3.x,Matplotlib,Radar Chart,一个善良聪明的人为我设计了一张漂亮的matplotlib雷达图。然而,这里的问题是图表上的条形图没有延伸到它们超过的给定ytick以下。理想情况下,高于1.0的每个值的条形都会向下延伸到中心,而不是留下间隙 我相信这里一定有一个简单的修复方法,但我对在matplotlib中创建雷达图的艺术非常业余 import matplotlib.pyplot as plt import numpy as np fig = plt.figure(figsize=(8, 8)) ax = fig.add_su

一个善良聪明的人为我设计了一张漂亮的matplotlib雷达图。然而,这里的问题是图表上的条形图没有延伸到它们超过的给定ytick以下。理想情况下,高于1.0的每个值的条形都会向下延伸到中心,而不是留下间隙

我相信这里一定有一个简单的修复方法,但我对在matplotlib中创建雷达图的艺术非常业余

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(figsize=(8, 8))
ax = fig.add_subplot(111, polar=True)

sample = [
    35.417256011315416,
    0.028288543140028287,
    1.3578500707213579,
    3.3663366336633667,
    0.8203677510608205,
    35.445544554455445,
    3.3946251768033946,
    19.46251768033946,
    0.7072135785007072,
]

N = len(sample)

theta = np.arange(0, 2 * np.pi, 2 * np.pi / N)
bars = ax.bar(theta, np.log10(sample), width=0.4)
ax.set_xticks(theta)
#ax.set_xticklabels(range(1, len(theta) + 1))
ax.set_xticklabels(['Delayed\nExecution', 'File\nOpening', 'Firewall\nModification', 'Permission\nModification', 'Persistence', 'Proxied\nExecution', 'Reconnaissance', 'Registry\nModification', 'Task\nStopping'])
ax.yaxis.grid(True)
precision = 2  # Change to your desired decimal precision

ax.set_yticklabels([str(round(10 ** x, precision)) for x in ax.get_yticks()])
#plt.ioff()
plt.show()

问题在于您的数据,
np.log10(示例)
返回一个正负值数组,因此,某些条不会扩展。为了让所有条形图从同一水平开始,您可以首先缩放
样本
,使最小的幅值为非负

get_mag = lambda x: 10**min(np.floor(np.log10(x)))
sample = np.array(sample) / get_mag(sample)
使用缩放的
样本
,您可以绘制数据

get_mag = lambda x: 10**min(np.floor(np.log10(x)))
init_mag = get_mag(sample)
sample = np.array(sample) / get_mag(sample)
N = len(sample)

theta = np.arange(0, 2 * np.pi, 2 * np.pi / N)
bars = ax.bar(theta, np.log10(sample), width=0.4)
ax.set_xticks(theta)
#ax.set_xticklabels(range(1, len(theta) + 1))
ax.set_xticklabels(['Delayed\nExecution', 'File\nOpening', 'Firewall\nModification', 'Permission\nModification', 'Persistence', 'Proxied\nExecution', 'Reconnaissance', 'Registry\nModification', 'Task\nStopping'])

dat = np.log10(sample)
ax.set_ylim(0,max(dat))
ax.yaxis.grid(True)
precision = 2  # Change to your desired decimal precision

ax.set_yticklabels([str(round((10 ** x) * init_mag, precision)) for x in ax.get_yticks()])
#plt.ioff()
plt.show()
输出是

注意,我还修改了yticks的标签

ax.set_yticklabels([str(round((10 ** x) * init_mag, precision)) for x in ax.get_yticks()])

你好这似乎很好,但Ytick与最初的样本列表不一致。例如,延迟执行是在9162而不是~30如果你能做到这一点,我很乐意打个绿色的勾:)@dipl0查看我的更新帖子:)