MBa*_*ith 5 matplotlib python-3.x pandas seaborn
我正在尝试绘制一些条形图,但想控制角的圆度。我尝试按照在 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()
Run Code Online (Sandbox Code Playgroud)
示例数据帧:
Completed Participants Completion
Event
Running 2 10 20.000000
Swimming 4 20 20.000000
Biking 3 35 8.571429
Hiking 7 10 70.000000
Run Code Online (Sandbox Code Playgroud)
电流输出:
期望输出:
只需稍微使用参数mutation_aspect和rounding_size,请记住,您的数据的维度是不同的。检查BoxStyle和FancyBboxPatch了解更多信息。
用实施例mutation_aspect==0.2和rounding_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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
870 次 |
| 最近记录: |