【问题标题】:change the format of the text of matplotlib clabel更改 matplotlib clabel 文本的格式
【发布时间】:2022-01-25 03:16:49
【问题描述】:

我正在绘制气压的轮廓。 一般来说,如果压力是1013 hPa,在等高线中会显示13,如果压力是997,则会显示97,即我需要获取最后两个字符。

我可以使用

plt.clabel(c, fmt="%.2s")

我可以得到前两个字符,但我不知道如何得到最后两个字。 请帮我解决这个问题,谢谢。

【问题讨论】:

  • official reference 中的示例可能会有所帮助。
  • 非常感谢,对您有帮助。

标签: python matplotlib


【解决方案1】:

格式可以是给定值返回格式化字符串的函数。

这是一个例子:

import matplotlib.pyplot as plt
import numpy as np
from scipy.ndimage.filters import gaussian_filter

Z = gaussian_filter(np.random.rand(100, 150), sigma=12) * 1000 + 500

fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(12, 4))

CS1 = ax1.contour(Z, cmap='inferno')
ax1.clabel(CS1, CS1.levels)
ax1.set_title('Default labels')
ax1.set_xticks([])
ax1.set_yticks([])

CS2 = ax2.contour(Z, cmap='inferno')
ax2.clabel(CS2, CS2.levels, fmt=lambda x: f'{x:.0f}'[-2:])
ax2.set_title('Using two last digits')
ax2.set_xticks([])
ax2.set_yticks([])

plt.tight_layout()
plt.show()

【讨论】:

  • 非常感谢,对您有帮助。
  • 请随意投票和/或mark答案被接受。
猜你喜欢
  • 2014-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-05
  • 2016-02-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多