占比#

import matplotlib.pyplot as plt
import numpy as np
import polars as pl
mpg = pl.read_csv("data/mpg.csv")
mpg.head()
shape: (5, 11)
manufacturermodeldisplyearcyltransdrvctyhwyflclass
strstrf64i64i64strstri64i64strstr
"audi""a4"1.819994"auto(l5)""f"1829"p""compact"
"audi""a4"1.819994"manual(m5)""f"2129"p""compact"
"audi""a4"2.020084"manual(m6)""f"2031"p""compact"
"audi""a4"2.020084"auto(av)""f"2130"p""compact"
"audi""a4"2.819996"auto(l5)""f"1626"p""compact"

Simple Pie Chart#

data = {
    "Scale": [
        ">300,000 tons per year",
        "100,000~300,000 tons per year",
        "<100,000 tons per year",
    ],
    "Proportion": ["0.2623", "0.2459", "0.4918"],
}

df = pl.DataFrame(data)
df.head()
shape: (3, 2)
ScaleProportion
strstr
">300,000 tons per year""0.2623"
"100,000~300,000 tons per year""0.2459"
"<100,000 tons per year""0.4918"
plt.pie(df["Proportion"], colors=["#bd4634", "#7fbd34bd", "#348ABD"], autopct="%.2f%%")

plt.legend(
    df["Scale"], title="Scale", bbox_to_anchor=(0.5, -0.45, 0.4, 0.5), frameon=False
)
<matplotlib.legend.Legend at 0x7f3fd7236270>
../_images/ffa49f867acc4712b125c7502b1b4c99365dd954f670ee03ed61a91bd65b0b58.png

Pie Chart with Convex#

mpg_group = mpg.group_by("class").len().with_row_index()
mpg_group
shape: (7, 3)
indexclasslen
u32stru32
0"subcompact"35
1"suv"62
2"compact"47
3"2seater"5
4"pickup"33
5"midsize"41
6"minivan"11
_, ax = plt.subplots(figsize=(12, 7), subplot_kw={"aspect": "equal"})

data = mpg_group["len"]
categories = mpg_group["class"]
explode = [0, 0, 0, 0, 0, 0.1, 0]


def func(pct, allvals) -> str:
    absolute = int(pct / 100.0 * allvals.sum())
    return f"{pct:.1f}% ({absolute})"


wedges, texts, autotexts = ax.pie(
    data,
    autopct=lambda pct: func(pct, data),
    textprops={"color": "w"},
    colors=plt.cm.Dark2.colors,
    startangle=140,
    explode=explode,
)

ax.legend(
    wedges,
    categories,
    title="Vehicle Class",
    loc="center left",
    bbox_to_anchor=(1, 0, 0.5, 1),
)
plt.setp(autotexts, size=10, weight=700)
ax.set(title="Class of Vehicles: Pie Chart")
plt.show()
../_images/1a31aaf61551b0b2b5e5e9aaea1f4c480541e4aafe8ffa295ad639e9c2004341.png

Pie Chart with Wedges#

colors = ["#f94144", "#f8961e", "#f9c74f", "#90be6d", "#2b1ac9", "#2994e0", "#94428d"]
wedgeprops = {
    "edgecolor": "k",
    "linewidth": 2,
    "linestyle": "solid",
    "antialiased": True,
}

categories = mpg_group["class"]
data = mpg_group["len"]

_, ax = plt.subplots(figsize=(6, 6), subplot_kw={"aspect": "equal"})

wedges, texts, autotexts = ax.pie(
    data,
    colors=colors,
    autopct="%1.1f%%",
    startangle=60,
    pctdistance=0.75,
    wedgeprops=wedgeprops,
    textprops={"fontsize": 10, "color": "white"},
)

ax.set(title="Class of Vehicles: Pie Chart")
bbox_props = {"boxstyle": "square, pad=0.3", "fc": "w", "ec": "w", "lw": 0.5}

kw = {
    "arrowprops": {"arrowstyle": "-"},
    "bbox": bbox_props,
    "zorder": 0,
    "va": "center",
}

for k, p in enumerate(wedges):
    ang = (p.theta2 - p.theta1) / 2.0 + p.theta1
    y = np.sin(np.deg2rad(ang))
    x = np.cos(np.deg2rad(ang))
    horizontalalignment = {-1: "right", 1: "left"}[int(np.sign(x))]
    connectionstyle = f"angle, angleA=0, angleB={ang}"
    kw["arrowprops"].update({"connectionstyle": connectionstyle})
    ax.annotate(
        categories[k],
        xy=(x, y),
        xytext=(1.2 * np.sign(x), 1.2 * y),
        horizontalalignment=horizontalalignment,
        **kw,
    )

plt.show()
../_images/4c27520049097eb5ed2a42e84fd8b0616a41b25c885076b87c00c0f703cad72a.png