带圆角的Seaborn barplot

时间:2020-05-03 02:33:51

标签: python-3.x pandas matplotlib seaborn

我正在尝试绘制一些条形,但想控制拐角的圆度。我尝试遵循堆栈问题Bar chart with rounded corners in Matplotlib中提供的答案,但似乎无法获得相同的结果。如何获得可以控制圆度的圆角边缘?还有更好的替代FancyBboxPatch吗?

下面是我的可测试代码以及​​当前和所需的输出。

我的代码:

[list[0], list[2], list[4]]

示例数据框:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.patches import FancyBboxPatch

mydict = {
    'Event': ['Running', 'Swimming', 'Biking', 'Hiking'],
    'Completed': [2, 4, 3, 7],
    'Participants': [10, 20, 35, 10]}

df = pd.DataFrame(mydict).set_index('Event')
df = df.assign(Completion=(df.Completed / df.Participants) * 100)
print(df)

plt.subplots(figsize=(5, 2))

sns.set_color_codes("pastel")
ax = sns.barplot(x=df.Completion, y=df.index, orient='h', joinstyle='bevel')

new_patches = []
for patch in reversed(ax.patches):
    bb = patch.get_bbox()
    color = patch.get_facecolor()
    p_bbox = FancyBboxPatch((bb.xmin, bb.ymin),
                            abs(bb.width), abs(bb.height),
                            boxstyle="round,pad=-0.0040,rounding_size=0.015",
                            ec="none", fc=color,
                            mutation_aspect=4
                            )
    patch.remove()
    new_patches.append(p_bbox)

for patch in new_patches:
    ax.add_patch(patch)

sns.despine(left=True, bottom=True)
ax.tick_params(axis=u'both', which=u'both', length=0)
plt.tight_layout()
plt.show()

当前输出:

enter image description here

所需的输出:

enter image description here

1 个答案:

答案 0 :(得分:5)

只需稍微使用参数mutation_aspectrounding_size,请记住数据的维度是不同的。检查BoxStyleFancyBboxPatch以获得更多信息。

带有mutation_aspect==0.2rounding_size=2的示例

plt.subplots(figsize=(5, 2))
sns.set_color_codes("pastel")
ax = sns.barplot(x=df.Completion, y=df.index, joinstyle='bevel')

new_patches = []
for patch in reversed(ax.patches):
    # print(bb.xmin, bb.ymin,abs(bb.width), abs(bb.height))
    bb = patch.get_bbox()
    color = patch.get_facecolor()
    p_bbox = FancyBboxPatch((bb.xmin, bb.ymin),
                            abs(bb.width), abs(bb.height),
                            boxstyle="round,pad=-0.0040,rounding_size=2",
                            ec="none", fc=color,
                            mutation_aspect=0.2
                            )
    patch.remove()
    new_patches.append(p_bbox)

for patch in new_patches:
    ax.add_patch(patch)

sns.despine(left=True, bottom=True)

ax.tick_params(axis=u'both', which=u'both', length=0)
plt.tight_layout()
# plt.savefig("data.png", bbox_inches="tight")
plt.show()

enter image description here