【发布时间】:2020-08-17 12:06:16
【问题描述】:
我正在尝试绘制一些条形图,但想控制角的圆度。我尝试按照堆栈问题Bar chart with rounded corners in Matplotlib 中提供的答案进行操作,但似乎无法得到相同的结果。如何让条形边缘具有圆角并控制圆度?还有更好的 FancyBboxPatch 替代品吗?
以下是我的可测试代码以及当前和所需的输出。
我的代码:
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()
示例数据框:
Completed Participants Completion
Event
Running 2 10 20.000000
Swimming 4 20 20.000000
Biking 3 35 8.571429
Hiking 7 10 70.000000
电流输出:
所需的输出:
【问题讨论】:
标签: python-3.x pandas matplotlib seaborn