Home > Net >  framing a pie chart in matplotlib
framing a pie chart in matplotlib

Time:04-12

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

CodePudding user response:

If I've understood your question right possible solution is the following:

# pip install matplotlib

import matplotlib.pyplot as plt
import numpy as np

# set chart style
plt.style.use('_mpl-gallery-nogrid')

# set data
x = [5, 2, 3, 4]

# set colors of segments
colors = plt.get_cmap('GnBu')(np.linspace(0.2, 0.7, len(x)))

# plot
fig, ax = plt.subplots()
ax.pie(x, colors=colors, radius=2, 
       wedgeprops={"linewidth": 2, "edgecolor": "black", 'antialiased': True}, # << HERE
       frame=False, startangle=0, autopct='%.1f%%', pctdistance=0.6)

plt.show()

enter image description here

CodePudding user response:

enter image description hereNot particularly elegant, but it works...

In [2]: for x in ax.get_xlim(): ax.axvline(x)
   ...: for y in ax.get_ylim(): ax.axhline(y)

CodePudding user response:

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

  • Related