如何在 matplotlib 中更改对数刻度刻度标签 [英] How to change log-scale tick labels in matplotlib

查看:92
本文介绍了如何在 matplotlib 中更改对数刻度刻度标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试更改matplotlib中对数图的刻度标签,通常通过手动设置标签可以很好地工作.但是,经常会出现下面显示的问题,手动移动标签似乎保留了一些旧标签.知道如何解决这个问题吗?

I am trying to change the tick labels of a log-plot in matplotlib, which often works fine by setting the labels manually. However, often the problem shown below occurs, manually moving the labels seems to keep some of the old labels. Any idea how to fix this?

import matplotlib.pyplot as plt
%matplotlib inline

fig, ax = plt.subplots()
x = [1, 10]
y = [0, 1]
ax.plot(x, y)
ax.set_xscale('log')
ax.set_xlim(0, 10)

ax.set_xticks([2.5, 7.5])

此外,我最近升级到了matplotlib 2.0.2,我不记得以前曾见过这种行为.

Also, I recently upgraded to matplotlib 2.0.2 and I cannot remember having seen this behaviour before.

推荐答案

显示的值是小刻度,要禁用它们,您可以声明:

The values shown are the minor ticks, to disable them, you can state:

ax.minorticks_off()

这将导致 7.5 的刻度标签也消失.

This will result in the tick label for 7.5 dissapearing as well.

您可能想要的是以下解决方案:

What you probably want, is the following solution:

from matplotlib.ticker import StrMethodFormatter, NullFormatter
ax.xaxis.set_major_formatter(StrMethodFormatter('{x:.1f}'))
ax.xaxis.set_minor_formatter(NullFormatter())

这篇关于如何在 matplotlib 中更改对数刻度刻度标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆