Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

framing a pie chart in matplotlib

I am desperately trying to add a "dark" border around this pie chart. I have tried the solutions described in plenty of questions here, but none turned out to add anything. You can find part of the attempts in the code:

import matplotlib.pyplot as plt
from cycler import cycler

plt.rc("axes", prop_cycle=cycler("color", ["darkgray", "gray", "lightgray"])
)
plt.rcParams["axes.edgecolor"] = "0.15"
plt.rcParams["axes.linewidth"]  = 1.25

labels = ["lab1", "lab2"]

sizes = [2000, 3000]
def make_autopct(values):
    def my_autopct(pct):
        total = sum(values)
        val = int(round(pct*total/100.0))
        s =  '{p:.2f}%({v:d}%)'.format(p=pct,v=val)
        s = f"${val}_{{\\ {pct:.2f}\%}}$"
        return s
    return my_autopct


fig, ax = plt.subplots(figsize=(10, 3))

ax.pie(sizes, explode=(0,0.02), labels=labels, autopct=make_autopct(sizes))
ax.set_title("title")
ax.patch.set_edgecolor('black')  
ax.patch.set_linewidth('1')  
plt.savefig("title.png")

enter image description here

like image 848
Antonio Sesto Avatar asked Oct 24 '25 04:10

Antonio Sesto


1 Answers

Below, three possibilities:

  • add a frame around pie patch:
ax.pie(sizes,
        explode=(0,0.02),
        labels=labels,
        autopct=make_autopct(sizes),
        frame=True)
  • add a border using axes coordinates (0, 0) to (1, 1) with fig.add_artist which draw on the fig object:
rect = pt.Rectangle((-0.1, -0.1), 1.2, 1.2,
                    fill=False, color="blue", lw=3, zorder=-1
                    transform=ax.transAxes)
fig.add_artist(rect)
  • add a border using fig coordinates (0, 0) to (1, 1) with fig.add_artist which draw on the fig object:
rect = pt.Rectangle((0.05, 0.05), .9, .9,
                    fill=False, ec="red", lw=1, zorder=-1,
                    transform=fig.transFigure)
fig.add_artist(rect)

Result:enter image description here

Edit This matplotlib's transformations page explains the different coordinate systems

like image 98
david Avatar answered Oct 26 '25 20:10

david



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!