How can I reduce the amount of decimals in contour plot legend?

Viewed 1291

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')

enter image description here

2 Answers

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()

example plot

PS: Even the official example from the documents show this strange formatting.

This should work.

fig, ax = plt.subplots()
w_field = np.genfromtxt('w_field.dat') 
CV = ax.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')

leg = ax.get_legend()

for lbl in leg.get_texts():
    label_text = lbl.get_text()
    float_num = label_text.split()[2]
    new_text = f'X = {float(float_num):,.1f}'
    lbl.set_text(new_text)
Related