【问题标题】:matplotlib tick axis notation with superscript带有上标的 matplotlib 刻度轴表示法
【发布时间】:2013-05-13 18:49:04
【问题描述】:

我想在频率上绘制一些图。我想要一个带有上标符号的 x 轴,例如 here。 此外,我需要带有垂直注释的垂直线,将千赫兹和兆赫兹分开。

import numpy as np
import matplotlib.pyplot as plt
band = np.linspace(0,10**12,100)
y = band

plt.plot(band,y)
plt.xlabel('Frequencies')

plt.vlines(10**3, min(y), max(y),colors = 'black', label = 'kilo Hz')
plt.vlines(10**6, min(y), max(y),colors = 'black', label = 'mega Hz')
plt.legend()
plt.show()

我尝试使用ticker,但不知道如何设置它。我尝试关注some 的示例,但遇到了AttributeError: 'Figure' object has no attribute 'ticklabel_format' 之类的错误 已经花了不少时间了,不知道怎么往前走。

一般来说,我需要以类似的方式格式化 x 轴,而不是 plt.xscale('log'),但我想保持线性比例。

【问题讨论】:

  • 你能展示使用不起作用的代码吗?
  • 另外,使用axvline 而不是vlines 作为垂直线。
  • 我尝试将matplotlib.ticker.Formatter 与不同的配置一起使用,并且尝试了很多不再存在的行。对于set_major_formatter,我也会收到类似object has no attribute的错误
  • 只是一个想法;如果您要使用 linear 比例的 x 轴跨越值(至少)从 103 到 106,则 105 和 106 将是 104 和 105 之间距离的 10 倍,以及 103 和 104 之间距离的 100 倍 (!!)。在您链接到的示例中,x 轴 实际上是对数刻度。
  • 但是您尝试set_major_formatter 的对象是什么?这是axis(不是axes)对象的方法。例如:yaxis = ax.get_yaxis()

标签: python matplotlib


【解决方案1】:

您可以将刻度线定义为字符串并分配它们:

mport numpy as np
import matplotlib.pyplot as plt
band = np.linspace(0,10**12,100)
y = band

plt.plot(band,y)
plt.xlabel("Frequencies")

plt.vlines(10**3, min(y), max(y),colors = 'black', label = 'kilo Hz')
plt.vlines(10**6, min(y), max(y),colors = 'black', label = 'mega Hz')

string_labels = []
for i in range(0,len(y),10):
    string_labels.append(r"$10^{%02d}$" % (i/10.0))

plt.xticks(np.linspace(0,10**12,10),string_labels)

plt.legend()
plt.show()

【讨论】:

  • 谢谢。我真的很喜欢你的解决方案。它提供了我需要的东西。我虽然可以从 matplotlib 级别进行某种格式化,但这也很好。
【解决方案2】:

我只是在黑暗中拍摄,但看起来 xlabel 有多种选择:

http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.xlabel

我去的时候:

http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.text

我注意到有一个垂直对齐选项。也许这就是你需要的?

【讨论】:

  • 谢谢,不幸的是,据我所知,我们无法解决我的问题
猜你喜欢
  • 2020-03-27
  • 2012-12-19
  • 2011-01-08
  • 1970-01-01
  • 1970-01-01
  • 2012-03-14
  • 1970-01-01
  • 2014-11-26
  • 1970-01-01
相关资源
最近更新 更多