matplotlib 图例标签中的保留空格
Reserved whitespace in matplotlib legend label
假设我有两个数组。
array1 = ['foofoo', 'bar']
array2 = ['foo', 'bar']
我可以打印这两个数组的每个可能组合。
for A in array1:
for B in array2:
print('{} {}'.format(A, B))
>>>
foofoo foo
foofoo bar
bar foo
bar bar
这很丑陋,所以我可以在打印时保留空格,以便第二部分对齐,如下所示:
for A in array1:
for B in array2:
print('{:7s} {}'.format(A, B))
>>>
foofoo foo
foofoo bar
bar foo
bar bar
那更漂亮了。我尝试对图例标签执行相同的操作,但它不起作用:
x = np.linspace(0,50, 100)
array1 = ['foofoo', 'bar']
array2 = ['foo', 'bar']
for A in array1:
for B in array2:
y = [random.random() for x in x]
y.sort()
legend_label = r"{:7s} {}".format(A, B)
plt.plot(x,y, label=legend_label)
plt.legend()
如何实现在 matplotlib 图例标签中保留空格的预期行为,以便我可以在列中对齐它,如 print('{:7s} {}'.format(A, B))
示例所示。
您需要使用等宽字体才能对齐字符数:
plt.legend(prop={'family': 'monospace'})
输出:
假设我有两个数组。
array1 = ['foofoo', 'bar']
array2 = ['foo', 'bar']
我可以打印这两个数组的每个可能组合。
for A in array1:
for B in array2:
print('{} {}'.format(A, B))
>>>
foofoo foo
foofoo bar
bar foo
bar bar
这很丑陋,所以我可以在打印时保留空格,以便第二部分对齐,如下所示:
for A in array1:
for B in array2:
print('{:7s} {}'.format(A, B))
>>>
foofoo foo
foofoo bar
bar foo
bar bar
那更漂亮了。我尝试对图例标签执行相同的操作,但它不起作用:
x = np.linspace(0,50, 100)
array1 = ['foofoo', 'bar']
array2 = ['foo', 'bar']
for A in array1:
for B in array2:
y = [random.random() for x in x]
y.sort()
legend_label = r"{:7s} {}".format(A, B)
plt.plot(x,y, label=legend_label)
plt.legend()
如何实现在 matplotlib 图例标签中保留空格的预期行为,以便我可以在列中对齐它,如 print('{:7s} {}'.format(A, B))
示例所示。
您需要使用等宽字体才能对齐字符数:
plt.legend(prop={'family': 'monospace'})
输出: