Matplotlib中带有圆角的条形图? [英] Bar chart with rounded corners in Matplotlib?
问题描述
如何创建带有圆角的条形图,如该图所示?可以用matplotlib完成吗?
How can I create a bar plot with rounded corners, like shown in this image? Can it be done with matplotlib?
推荐答案
似乎无法直接在条形图中添加圆角.但是matplotlib确实提供了 FancyBboxPatch
类的演示程序,此处.
It looks like there's no way to directly add rounded corners to a bar chart. But matplotlib does provide a FancyBboxPatch
class a demo of which is available here.
因此,为了创建一个如问题所示的图表,我们首先可以制作一个简单的水平条形图:
So in order to create a plot like shown in the question we could first make a simple horizontal bar chart:
import pandas as pd
import numpy as np
# make up some example data
np.random.seed(0)
df = pd.DataFrame(np.random.uniform(0,20, size=(4,4)))
df = df.div(df.sum(1), axis=0)
# plot a stacked horizontal bar chart
ax = df.plot.barh(stacked=True, width=0.98, legend=False)
ax.figure.set_size_inches(6,6)
这将产生以下情节:
为了使矩形具有圆角,我们可以遍历ax.patches
中的每个矩形补丁并将其替换为FancyBboxPatch
.这个带有圆角的新花哨补丁可复制旧补丁的位置和颜色,因此我们不必担心放置.
In order to make the rectangles have rounded corners we could go through every rectangle patch in ax.patches
and replace it with a FancyBboxPatch
. This new fancy patch with rounded corners copies location and color from the old patch so that we don't have to worry about placement.
from matplotlib.patches import FancyBboxPatch
ax = df.plot.barh(stacked=True, width=1, legend=False)
ax.figure.set_size_inches(6,6)
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)
这就是我们得到的:
我给盒子加上了负填充物,以使条形之间留有空隙.这些数字有点黑魔法.不知道rounding_size
和pad
的单位是什么.在上一个演示示例中显示了mutation_aspect
,在这里我将其设置为4,因为y
范围约为4,而x
范围约为1.
I gave the boxes a negative padding so that there are gaps between bars. The numbers are a bit of black magic. No idea what the unit is for rounding_size
and pad
. The mutation_aspect
is shown in the last demo example, here I set it to 4 because y
range is about 4 while x
range is approximately 1.
这篇关于Matplotlib中带有圆角的条形图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!