Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 605
Laura Kornberger Avatar asked Oct 18 '25 14:10

Laura Kornberger


1 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.

like image 58
JohanC Avatar answered Oct 20 '25 05:10

JohanC