【问题标题】:How to set ticks on Fixed Position , matplotlib如何在固定位置上设置刻度,matplotlib
【发布时间】:2013-06-16 03:33:20
【问题描述】:

谁能帮我使用 matplotlib 将刻度设置在固定位置?正如本教程所述,我已尝试使用 FixedPosition:

ax = pl.gca()
ax.xaxis.set_major_locator(eval(locator))

http://scipy-lectures.github.io/intro/matplotlib/matplotlib.html#figures-subplots-axes-and-ticks

但是当我尝试运行时,它告诉我 set_major_locator 方法不存在。

一个简单的例子会很有用。

谢谢。

【问题讨论】:

  • 该链接断章取义。使用eval 可能会非常聪明地生成他们的示例图,目前还不清楚locator 的值是什么。

标签: python matplotlib


【解决方案1】:

只需使用ax.set_xticks(positions)ax.set_yticks(positions)

例如:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.set_xticks([0.15, 0.68, 0.97])
ax.set_yticks([0.2, 0.55, 0.76])
plt.show()

【讨论】:

  • 此方法将删除我在绘图上的现有刻度。如果我想在不影响现有刻度的情况下添加这些额外刻度怎么办?
  • @dnth:您可以通过twinx()twiny() 图表创建一个新轴,刻度位于另一侧。
  • @dnth 您可以使用locs = ax.xaxis.get_ticklocs() 获取位置,修改该列表以添加您想要的刻度,然后按照乔的建议使用ax.set_xticks(locs)
【解决方案2】:
import numpy as np
import matplotlib.ticker as ticker
import matplotlib.pyplot as plt

name_list = ('Omar', 'Serguey', 'Max', 'Zhou', 'Abidin')
value_list = np.random.randint(0, 99, size = len(name_list))
pos_list = np.arange(len(name_list))

ax = plt.axes()
ax.xaxis.set_major_locator(ticker.FixedLocator((pos_list)))
ax.xaxis.set_major_formatter(ticker.FixedFormatter((name_list)))
plt.bar(pos_list, value_list, color = '.75', align = 'center')

plt.show()

【讨论】:

  • 需要详细说明吗?
  • 这很有帮助。
  • 如果可以的话,我会给这个答案五个赞成票。这真的很有帮助。如果有人在寻找解释,set_major_locator() 方法根据列表 pos_list 设置图形中刻度的位置,并根据 pos_list 设置刻度标签。现在要取回旧的刻度标签,正在使用 set_major_formatter()。
猜你喜欢
  • 1970-01-01
  • 2018-09-08
  • 1970-01-01
  • 2020-10-01
  • 1970-01-01
  • 2018-06-11
  • 2013-02-21
  • 1970-01-01
  • 2011-09-23
相关资源
最近更新 更多