我正在matplotlib使用from matplotlib.patches import Patch类在图中添加补丁。请参阅下面的示例代码-
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Patch
n = 5
hatch_1 = 'o'
hatch_2 = '.'
opacity = 0.4
bar_width = 0.4
y = np.random.randint(low=0, high=10, size=n)
x = np.arange(n)
bars = plt.bar(x, y, bar_width, align='center', alpha=opacity, fill=False)
for bar in bars:
bar.set_hatch(hatch_1)
y = np.random.randint(low=0, high=10, size=n)
bars = plt.bar(x + bar_width, y, bar_width,
align='center', alpha=opacity, fill=False)
for bar in bars:
bar.set_hatch(hatch_2)
patch_1 = Patch(fill=False, label='Hatch 1', hatch=hatch_1, alpha=opacity)
patch_2 = Patch(fill=False, label='Hatch 2', hatch=hatch_2, alpha=opacity)
# add legends
plt.legend(handles=[patch_1, patch_2], loc='upper right')
plt.show()
Run Code Online (Sandbox Code Playgroud)
用于图例的舱口不可见。我想如果我把补丁做得更大,它会是可见的。
如何使补丁更大?
您可以通过多种方式更改图例补丁的大小。
首先,您可以使用handlelength选项增加宽度plt.legend。
但是,无法使用 kwargs 增加它们的高度。所以我们需要在创建图例后遍历补丁。如果我们在创建图例时保留对图例的引用leg = plt.legend(...),那么我们可以使用for patch in leg.get_patches():.
然后您可以使用 更改补丁的高度patch.set_height()。
然而,所有这些修补意味着它们不会完全正确对齐。所以我们还需要稍微改变它们的垂直位置(使用patch.set_y())。
我还发现它有助于增加图例中标签的垂直间距以很好地适应(使用labelspacingkwarg)。
最后,我在图例标签的开头添加了一个新行,使其看起来不错 ( label='\nHatch 1')。
完整的脚本如下。你不妨玩弄的值labelspacing,handlelength,patch.set_height()并patch.set_y()满足您的需求。
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Patch
n = 5
hatch_1 = 'o'
hatch_2 = '.'
opacity = 0.4
bar_width = 0.4
y = np.random.randint(low=0, high=10, size=n)
x = np.arange(n)
bars = plt.bar(x, y, bar_width, align='center', alpha=opacity, fill=False)
for bar in bars:
bar.set_hatch(hatch_1)
y = np.random.randint(low=0, high=10, size=n)
bars = plt.bar(x + bar_width, y, bar_width,
align='center', alpha=opacity, fill=False)
for bar in bars:
bar.set_hatch(hatch_2)
patch_1 = Patch(fill=False, label='\nHatch 1', hatch=hatch_1, alpha=opacity)
patch_2 = Patch(fill=False, label='\nHatch 2', hatch=hatch_2, alpha=opacity)
# add legends
leg = plt.legend(handles=[patch_1, patch_2], loc='upper right', labelspacing=1.5, handlelength=4)
for patch in leg.get_patches():
patch.set_height(22)
patch.set_y(-6)
plt.show()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2540 次 |
| 最近记录: |