通过在matplotlib中用X替换数字来隐藏数字的第一个值

问题描述

我有给我以下代码代码

import matplotlib.pyplot as plt
plt.figure(figsize=(7,3))
plt.plot([-2,-1,1,2],[5004,5006,5002,5007,5001])
plt.show()

enter image description here

我想用X替换y轴上第一个数字的值(5001> X001,5002> X002,依此类推)。

enter image description here

是否可以在matplotlib中自动执行此操作?

解决方法

您可以使用FuncFormatter模块中的matplotlib.ticker

从文档中

该函数应该接受两个输入(刻度值x和位置pos),并返回包含相应刻度标签的字符串。

因此,这只是操纵刻度值x,并将第一个字符更改为“ X”的情况。

例如:

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

fig = plt.figure(figsize=(7,3))
ax = fig.add_subplot()

ax.plot([-2,-1,1,2],[5004,5006,5002,5007,5001])

ax.yaxis.set_major_formatter(ticker.FuncFormatter(
        lambda x,pos: '{}{}'.format('X',str(int(x))[1:])))

plt.show()

enter image description here

注意:为方便起见,set_major_formatter可以直接将一个函数用作其输入,无论如何它将被转换为FuncFormatter。因此,您可以避免导入ticker模块。您可以将上面的示例简化为:

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(7,5001])

ax.yaxis.set_major_formatter(lambda x,str(int(x))[1:]))
plt.show()
,

我遵循了matplotlib的this指南,并将其应用于您的示例。我找到了一个名为FuncFormatter的简洁类,可以代替指南中的类使用。该类需要一个以xpos作为参数的可调用对象,只要我们返回一个字符串,我们就可以做任何想做的事情。

import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter

fig,ax = plt.subplots()
ax.plot([-2,5001])
ax.yaxis.set_major_formatter(FuncFormatter(lambda x,pos: f"X{str(int(x))[1:]}"))
plt.show()

New plot