Seaborn or Matplotlib Boxplot with rounded corners

Viewed 455

I'd like to do a boxplot with rounded corners but not sure how. Saw a post to make rounded corners for barplot but no luck with boxplot. ax.artists is a list of matplotlib.patches.PathPatch objects and I think they control the box styles.

Below is some sample code

import pandas as pd 
import numpy as np 
import seaborn as sns 
df = pd.DataFrame(np.random.rand(100, 1), columns=['value'])
df['type'] = pd.Series(np.repeat(['type1','type2', 'type3', 'type4'], 25))
ax = sns.boxplot(data=df, x="type", y="value")
1 Answers

There are similar questions (e.g. Bar chart with rounded corners and Seaborn barplot with rounded corners). These solutions need quite some adaptions to be usable here.

The boxplot's rectangles aren't stored as rectangles, but as patch artists. To get their bounding box, the entent of their path needs to be calculated.

The parameters of FancyBboxPatch need some experimenting. Setting pad=0 makes the rounded rectangle occupy the same space. mutation_aspect (defaults to 1) is needed to make the vertical boxes look well. For your own application, some fine-tuning might be needed.

from matplotlib import pyplot as plt
from matplotlib.patches import FancyBboxPatch
from matplotlib.path import get_path_collection_extents
import seaborn as sns
import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.rand(100, 1), columns=['value'])
df['type'] = pd.Series(np.repeat(['type1', 'type2', 'type3', 'type4'], 25))
ax = sns.boxplot(data=df, x="type", y="value")

new_patches = []
for patch in reversed(ax.artists):
    bb = patch.get_path().get_extents()
    color = patch.get_facecolor()
    p_bbox = FancyBboxPatch((bb.xmin, bb.ymin),
                            abs(bb.width), abs(bb.height),
                            boxstyle="round,pad=0,rounding_size=0.2",
                            ec="black", fc=color,
                            mutation_aspect=0.2)
    patch.remove()
    new_patches.append(p_bbox)
for patch in new_patches:
    ax.add_patch(patch)
plt.show()

seaborn boxplot with rounded corners

Related