I am trying to create a neat legend in Pyplot. So far I have this:
fig = plt.figure()
ax = plt.gca()
marker_size = [20.0, 40.0, 60.0, 100.0, 150.0]
marker_color = ['black', 'red', 'pink', 'white', 'yellow']
ranges = [0.0, 1.5, 20.0, 60.0, 500.0]
marker_edge_thickness = 1.2
s = [(m ** 2) / 100.0 for m in marker_size]
scatter_kwargs = {'edgecolors' : 'k', 'linewidths' : marker_edge_thickness}
for i in range(len(marker_size)):
if i == (len(marker_size) - 1):
label_str = '{:>5.1f} $\leq$ H$_2$'.format(ranges[i])
else:
label_str = '{:>5.1f} $\leq$ H$_2$ < {:>5.1f}'.format(ranges[i], ranges[i 1])
ax.scatter([], [], s = s[i], c = marker_color[i],
label = label_str, **scatter_kwargs)
#ax.legend(prop={'family': 'monospace'})
ax.legend()
plt.show()
It is ok but the symbols don't align properly between the rows. I would like to align the rows at multiple points, with alignment on the decimal points, the less-than and greater-than symbols, and the H2. I could use a monotype font (as per this answer:
CodePudding user response:
This uses monospace type, but at least uses the appropriate font for the subscript of H
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = plt.gca()
marker_size = [20.0, 40.0, 60.0, 100.0, 150.0]
marker_color = ['black', 'red', 'pink', 'white', 'yellow']
ranges = [0.0, 1.5, 20.0, 60.0, 500.0]
num_digits = [1,1,2,2,3]
marker_edge_thickness = 1.2
s = [(m ** 2) / 100.0 for m in marker_size]
scatter_kwargs = {'edgecolors' : 'k', 'linewidths' : marker_edge_thickness}
for i in range(len(marker_size)):
if i == (len(marker_size) - 1):
label_str = '{:.1f}$\leq \mathregular{}$'.format(ranges[i],r'{\ H_2\ }')
else:
label_str = '{:>5.1f}$\leq \mathregular{}<${:>5.1f}'.format(ranges[i], r'{\ H_2\ }',ranges[i 1])
ax.scatter([], [], s = s[i], c = marker_color[i],
label = label_str, **scatter_kwargs)
ax.legend(prop={'family': 'monospace'})
Result: