首页 > 解决方案 > 如何减少等高线图图例中的小数位数?

问题描述

我试图为图例获得小数点后一位。绘图所基于的数据 (w_field) 具有 8 位小数的值。

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

在此处输入图像描述

标签: pythonmatplotliblegend

解决方案


该函数CV.legend_elements()接受一个格式化参数,该参数应该是一个返回格式化字符串的函数。这是一个示例,显示了与默认格式的区别。

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:即使是文档中的官方示例也显示了这种奇怪的格式。


推荐阅读