【问题标题】:Put a function of x as the x tick labels [duplicate]将x的函数作为x刻度标签[重复]
【发布时间】:2014-06-05 08:18:14
【问题描述】:

假设我有两个 numpy 数组 xy,我想绘制一条简单的 y 曲线作为 x 的函数。在y 轴上,我想把y 的值(作为标签),但在x 轴上,我想把值的一些函数作为标签。

例如,如果 x=array([1, 2, 4, 8, 16])y=array([1, 2, 1, 2, 1]),我想为 xticks 分配标签,这将是以下字符串格式的结果:

lambda x_val: "$2^{{+{:.0f}}}$".format(log2(x_val))

但我对通用解决方案感兴趣。

【问题讨论】:

  • 如果您不同意重复投票,请联系我。
  • @tcaswell - 不,我同意,谢谢...
  • 太棒了。一票接近重复的权力非常有用,但比我真正想要的权力要大一点。

标签: python matplotlib


【解决方案1】:

使用matplotlib.ticker.FuncFormatter。无耻地复制和改编 custom ticker 示例,这样的事情可能会奏效:

from matplotlib.ticker import FuncFormatter
import matplotlib.pyplot as plt
from matplotlib import rc
import numpy as np

rc('text', usetex=True)

formatter = FuncFormatter(lambda x_val, tick_pos: "$2^{{+{:.0f}}}$".format(np.log2(x_val)))

x = np.array([1, 2, 4, 8, 16])
y = np.array([1, 2, 1, 2, 1])
fig, ax = plt.subplots()
ax.xaxis.set_major_formatter(formatter)
plt.plot(x, y)
plt.show()

导致

注意第一个标签是坏的;运行代码时会发出除以零警告。这是因为 matplotlib 在 0 到 16 之间缩放轴,并在 0 处放置一个刻度线(然后将其传递给格式化程序)。您可以关闭该刻度线,或以不同方式缩放 x 轴以避免这种情况。

【讨论】:

  • 我不确定 - 我的 x 数组中的 1 应该有什么问题?
  • @Bach 你是对的,这不是输入数据。这是 matplotlib 自动缩放 x 轴的原因。我已经据此更新了我的答案。
【解决方案2】:

对于您给出的案例:

import matplotlib.pylab as plt
import numpy as np

x = np.array([1, 2, 4, 8, 16]) 
y = np.array([1, 2, 1, 2, 1])

ax = plt.subplot()
ax.plot(x, y)

ax.set_xticks(x)
ax.set_xticklabels(["$2^{{+{:.0f}}}$".format(np.log2(x_val)) for x_val in x])

plt.show()

对于更通用的解决方案,您需要指定 x_values 您希望刻度为 x 通常会有比你想要的多得多的点数。手动指定它,或者您可以调用ax.get_xticklabels() 以获取matplotlib 以返回自动滴答点。

对于最通用的方法,您只需告诉 matplotlib 您希望如何格式化刻度,然后参见 Jake Vanderplas tutorialexample in the docs 的格式化部分。

【讨论】:

  • 使用set_*ticklabels 通常是危险的,因为它将标签与数据坐标分离(唯一合理的用途是将文本标签放在条形图上,其中 x 单位无论如何都是无意义的)。
猜你喜欢
  • 2017-09-20
  • 2011-03-28
  • 1970-01-01
  • 2012-03-14
  • 2020-03-29
  • 1970-01-01
  • 1970-01-01
  • 2013-03-24
  • 1970-01-01
相关资源
最近更新 更多