I'm trying to get just one decimal place for the legend. The data which the plot is based on (w_field) has values with 8 decimal places.
w_field = np.genfromtxt('w_field.dat')
CV = plt.contour(w_field)
x,Vel = CV.legend_elements()
plt.legend(x,Vel, title= 'Vertical velocity (m/s)', fontsize= 10, bbox_to_anchor=(1.05, 1), loc='upper left')
plt.xlabel('Nx')
plt.ylabel('Ny')
The function CV.legend_elements()
accepts a formatting parameter, which should be a function returning a formatted string. Here is an example, showing the difference with the default formatting.
from matplotlib import pyplot as plt
import numpy as np
w_field = np.random.randn(60, 100).cumsum(axis=1).cumsum(axis=0) / 50
CV = plt.contour(w_field)
x, Vel = CV.legend_elements()
legend1 = plt.legend(x, Vel, title='Default formatting', fontsize=10, bbox_to_anchor=(1.02, 1.02), loc='upper left')
x, Vel = CV.legend_elements(str_format=lambda x: f'{x:.1f}')
plt.legend(x, Vel, title='With formatting function', fontsize=10, bbox_to_anchor=(1.02, 0), loc='lower left')
plt.gca().add_artist(legend1) # matplotlib removes the legend when a second legend is created, here it is added again
plt.tight_layout()
plt.show()
PS: Even the official example from the documents show this strange formatting.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With