【问题标题】:How to create Pie charts with different sized slices in Python?如何在 Python 中创建具有不同大小切片的饼图?
【发布时间】:2021-05-25 23:23:40
【问题描述】:

我想写一些足球运动员的球探报告,为此我需要可视化。其中一种类型是饼图。现在我需要一些如下所示的饼图,具有不同大小的切片(与切片所指示的事物的数量成比例)。任何人都可以建议如何做到这一点或有任何链接到我可以学习的网站吗?

Pie charts with different size of slices

【问题讨论】:

  • (顺便说一句,您要查找的术语是rose diagram
  • 谢谢伙计。不知道真名

标签: python matplotlib charts pie-chart


【解决方案1】:

您要查找的内容称为“雷达饼图”。它类似于更常用的“雷达图”,但我认为它看起来更好,因为它突出了值,而不是专注于无意义的形状。

您在使用足球数据集时面临的挑战是每个类别的规模都不同,因此您希望将每个值绘制为某个最大值的百分比。我的代码将完成此操作,但您需要注释原始值以完成这些图表。

绘图本身可以通过使用极轴的标准 matplotlib 库来完成。我从这里借用了代码 (https://raphaelletseng.medium.com/getting-to-know-matplotlib-and-python-docx-5ee67bad38d2)。

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from math import pi

from random import random, seed
seed(12345)

# Generate dataset with 10 rows, different maxes
maxes = [5, 5, 5, 2, 2, 10, 10, 10, 10, 10]
df = pd.DataFrame(
    data = {
        'categories': ['category_{}'.format(x) for x, _ in enumerate(maxes)],
        'scores': [random()*max for max in maxes],
        'max_values': maxes,
    },
)
df['pct'] = df['scores'] / df['max_values']
df = df.set_index('categories')

# Plot pie radar chart
N = df.shape[0]
theta = np.linspace(0.0, 2*np.pi, N, endpoint=False)
categories = df.index
df['radar_angles'] = theta

ax = plt.subplot(polar=True)
ax.bar(df['radar_angles'], df['pct'], width=2*pi/N, linewidth=2, edgecolor='k', alpha=0.5)
ax.set_xticks(theta)
ax.set_xticklabels(categories)
_ = ax.set_yticklabels([])

【讨论】:

    【解决方案2】:

    我之前曾与rosepolar bar chart 合作过。这是一个例子。

    import plotly.express as px
    df = px.data.wind()
    fig = px.bar_polar(df, r="frequency", theta="direction",
                       color="strength", template="plotly_dark",
                       color_discrete_sequence= px.colors.sequential.Plasma_r)
    fig.show()
    

    【讨论】:

    • 示例代码会有很大帮助。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    • 2018-07-09
    相关资源
    最近更新 更多