【问题标题】:Seaborn or Matplotlib Boxplot with rounded cornersSeaborn 或 Matplotlib 圆角箱线图
【发布时间】:2021-08-12 23:11:00
【问题描述】:

我想做一个圆角的boxplot,但不知道怎么做。看到一个帖子为条形图制作圆角,但箱形图没有运气。 ax.artists 是 matplotlib.patches.PathPatch 对象的列表,我认为它们控制框样式。

下面是一些示例代码

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")

【问题讨论】:

标签: python pandas matplotlib seaborn


【解决方案1】:

有类似的问题(例如Bar chart with rounded cornersSeaborn barplot with rounded corners)。这些解决方案需要进行相当多的调整才能在此处使用。

箱线图的矩形不存储为矩形,而是作为补丁艺术家。为了得到他们的边界框,需要计算他们的路径的entent。

FancyBboxPatch 的参数需要做一些实验。设置pad=0 使圆角矩形占据相同的空间。需要mutation_aspect(默认为1)才能使垂直框看起来不错。对于您自己的应用程序,可能需要进行一些微调。

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()

【讨论】:

  • 我试图从相同的答案中调整它,但它完全不在我的掌控之中。 get_extents() 是我学到的。 +1
  • 非常感谢您的回答!这正是我想要的。对于调整参数,我不太了解这些参数的作用,但几个 for 循环解决了它。这个demo 很有帮助。
猜你喜欢
  • 2020-02-21
  • 2020-09-16
  • 2019-12-07
  • 2023-01-18
  • 1970-01-01
  • 1970-01-01
  • 2017-05-14
  • 2021-03-08
  • 1970-01-01
相关资源
最近更新 更多