使用对数刻度设置刻度线

问题描述 投票:55回答:3

似乎set_xticks不能以对数刻度运行​​:

from matplotlib import pyplot as plt
fig1, ax1 = plt.subplots()
ax1.plot([10, 100, 1000], [1,2,3])
ax1.set_xscale('log')
ax1.set_xticks([20, 200, 500])
plt.show()

可能吗?

matplotlib plot logarithm
3个回答
60
投票
import matplotlib
from matplotlib import pyplot as plt
fig1, ax1 = plt.subplots()
ax1.plot([10, 100, 1000], [1,2,3])
ax1.set_xscale('log')
ax1.set_xticks([20, 200, 500])
ax1.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())

ax1.get_xaxis().get_major_formatter().labelOnlyBase = False
plt.show()

resulting plot


13
投票

我将添加一些绘图并显示如何删除较小的刻度线:

OP:

from matplotlib import pyplot as plt

fig1, ax1 = plt.subplots()
ax1.plot([10, 100, 1000], [1,2,3])
ax1.set_xscale('log')
ax1.set_xticks([20, 300, 500])
plt.show()

enter image description here

要添加一些特定的报价,如tcaswell所指出的,可以使用matplotlib.ticker.ScalarFormatter

matplotlib.ticker.ScalarFormatter

from matplotlib import pyplot as plt import matplotlib.ticker fig1, ax1 = plt.subplots() ax1.plot([10, 100, 1000], [1,2,3]) ax1.set_xscale('log') ax1.set_xticks([20, 300, 500]) ax1.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter()) plt.show()

要删除较小的刻度线,可以使用enter image description here

matplotlib.rcParams['xtick.minor.size']

matplotlib.rcParams['xtick.minor.size']

您可以改用from matplotlib import pyplot as plt import matplotlib.ticker matplotlib.rcParams['xtick.minor.size'] = 0 matplotlib.rcParams['xtick.minor.width'] = 0 fig1, ax1 = plt.subplots() ax1.plot([10, 100, 1000], [1,2,3]) ax1.set_xscale('log') ax1.set_xticks([20, 300, 500]) ax1.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter()) plt.show() ,它具有相同的效果(但仅修改当前轴,与enter image description here不同,不是所有将来的图形):

ax1.get_xaxis().set_tick_params

ax1.get_xaxis().set_tick_params


4
投票

matplotlib.rcParams有效,如果您仔细观察,它会将主要刻度线设置为20、200、500(刻度线比其他刻度线更长)。与相同的图进行比较,而无需调用from matplotlib import pyplot as plt import matplotlib.ticker fig1, ax1 = plt.subplots() ax1.plot([10, 100, 1000], [1,2,3]) ax1.set_xscale('log') ax1.set_xticks([20, 300, 500]) ax1.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter()) ax1.get_xaxis().set_tick_params(which='minor', size=0) ax1.get_xaxis().set_tick_params(which='minor', width=0) plt.show()

重点是enter image description here设置刻度,而不是刻度标签。如果要添加标签,请添加]​​>

set_xticks

在plt.show()之前)>

© www.soinside.com 2019 - 2024. All rights reserved.