matplotlib 如何用对数刻度显示所有主要和次要刻度标签[重复]

rn0zuynd  于 2023-08-06  发布在  其他
关注(0)|答案(1)|浏览(80)

此问题在此处已有答案

Matplotlib so log axis only has minor tick mark labels at specified points. Also change size of tick labels in colorbar(2个答案)
Matplotlib semi-log plot: minor tick marks are gone when range is large(5个答案)
kilo (K) and mega (M) suffixes on matplotlib's axes(2个答案)
Make tick labels font size smaller(10个答案)
Rotate axis tick labels(13个回答)
16天前关闭
我正试着画一个x轴是对数的xy图。我使用这个命令:

import matplotlib as plt
plt.plot(X,Y)
plt.xscale('log')

字符串
x轴是对数的,但只有10的倍数的值才显示在图形中,但我需要在图形中显示所有网格线的值。


的数据
如图所示,x轴上只显示10^6,但我需要显示其他点的值。

3npbholx

3npbholx1#

*python 3.11.4matplotlib 3.7.1中测试

  • 根据副本:
  • answer验证是否显示所有主要和次要刻度。
  • 这个answer展示了如何格式化和显示次要xtick标签。
  • 如图所示,包括次x刻度标签会聚集x轴。
  • 这个answer展示了如何通过选择性地设置subs(例如:subs=[.2, .4, .6, .8])。
import matplotlib.pyplot as plt
import matplotlib.ticker as tkr
import numpy as np

y = np.arange(11)
x = 10.0**y

fig, ax = plt.subplots(figsize=(25, 6))

ax.semilogx(x, y)

# show all minor and major xticks, and all major xtick labels
ax.xaxis.set_major_locator(tkr.LogLocator(numticks=999))
ax.xaxis.set_minor_locator(tkr.LogLocator(numticks=999, subs="all"))

# remove this line to remove the minor xtick labels
ax.xaxis.set_minor_formatter(tkr.FormatStrFormatter('%d'))

字符串


的数据

  • 在Stack Overflow上有很多问题,讨论了自定义格式化程序的使用。
  • .set_minor_formatter
  • .set_major_formatter
  • 交换xy,设置次要刻度标签格式和字体大小,可以改善视觉体验。
y = np.arange(11)
x = 10.0**y

fig, ax = plt.subplots(figsize=(10, 20))

# swap x and y
ax.semilogy(y, x)

ax.yaxis.set_major_locator(tkr.LogLocator(numticks=999))
ax.yaxis.set_minor_locator(tkr.LogLocator(numticks=999, subs="all"))

# adjust the minor label format
mkfunc = lambda x, pos: '%1.0fM' % (x * 1e-6) if x >= 1e6 else '%1.0fK' % (x * 1e-3) if x >= 1e3 else '%1.0f' % x
mkformatter = tkr.FuncFormatter(mkfunc)
ax.yaxis.set_minor_formatter(mkformatter)

# adjust the font size
ax.yaxis.set_tick_params(which='minor', labelsize=5)
ax.yaxis.set_tick_params(which='major', labelsize=8)

# set the y limits
ax.set_ylim(1, 10**10)

# save figure
fig.savefig('logscale.png')


y = np.arange(11)
x = 10.0**y

fig, ax = plt.subplots(figsize=(25, 6))
ax.semilogx(x, y)

ax.xaxis.set_major_locator(tkr.LogLocator(numticks=999))
ax.xaxis.set_minor_locator(tkr.LogLocator(numticks=999, subs="all"))

mkfunc = lambda x, pos: '%1.0fM' % (x * 1e-6) if x >= 1e6 else '%1.0fK' % (x * 1e-3) if x >= 1e3 else '%1.0f' % x
mkformatter = tkr.FuncFormatter(mkfunc)
ax.xaxis.set_minor_formatter(mkformatter)

# set the minor xtick label rotation (in this case, the implicit pyplot command is easiest)
plt.xticks(rotation=90, ha='right', minor=True)

# adjust the font size
ax.xaxis.set_tick_params(which='minor', labelsize=5)
ax.xaxis.set_tick_params(which='major', labelsize=8)

ax.set_xlim(1, 10**10)

fig.savefig('logscale.png')


相关问题