python - 如何减少等高线图图例中的小数位数?
问题描述
我试图为图例获得小数点后一位。绘图所基于的数据 (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')
解决方案
该函数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:即使是文档中的官方示例也显示了这种奇怪的格式。
推荐阅读
- c# - 从内存中删除 UTF 字节的方法?
- python - 如何组合列表并使用条件语句将它们打印出来?Python
- ios - 插入新单元格时,iOS UITableView 删除的单元格内容重新出现
- python - 使用 Pickle 将列表写入文件
- wso2 - 在 WSO2 API Manager 的 Publisher 门户或 API Publisher 中获取用户角色
- html - Flask favicon 无法在 Google Chrome 上运行
- excel - 查找 2 列的总数,然后在 excel 中查找平均值
- apache-spark - Pyspark 错误 - 在 AWS EMR 上找不到压缩编解码器 com.hadoop.compression.lzo.LzoCodec
- ruby - `:|` 在 Ruby 中的作用是什么?
- python - 比较 Numpy 中的负指数和正指数