在matplotlib中按因子更改打印比例

2024-04-30 00:31:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python创建一个情节。有没有办法根据某个因素重新调整轴的比例?yscalexscale命令只允许我关闭日志缩放。

编辑:
例如。如果我有一个x标度从1nm到50nm的图,那么x标度的范围是1x10^(-9)到50x10^(-9),我希望它从1变为50。因此,我希望plot函数将放在绘图上的x值除以10^(-9)


Tags: 函数命令编辑绘图plot比例因素情节
3条回答

正如您所注意到的,xscaleyscale不支持简单的线性重新缩放(不幸的是)。作为Hooked答案的替代方案,您可以欺骗标签,比如:

ticks = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x*scale))
ax.xaxis.set_major_formatter(ticks)

显示x和y缩放的完整示例:

import numpy as np
import pylab as plt
import matplotlib.ticker as ticker

# Generate data
x = np.linspace(0, 1e-9)
y = 1e3*np.sin(2*np.pi*x/1e-9) # one period, 1k amplitude

# setup figures
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
# plot two identical plots
ax1.plot(x, y)
ax2.plot(x, y)

# Change only ax2
scale_x = 1e-9
scale_y = 1e3
ticks_x = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x/scale_x))
ax2.xaxis.set_major_formatter(ticks_x)

ticks_y = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x/scale_y))
ax2.yaxis.set_major_formatter(ticks_y)

ax1.set_xlabel("meters")
ax1.set_ylabel('volt')
ax2.set_xlabel("nanometers")
ax2.set_ylabel('kilovolt')

plt.show() 

最后我得到了一张照片的学分:

Left: ax1 no scaling, right: ax2 y axis scaled to kilo and x axis scaled to nano

注意,如果像我一样有text.usetex: true,您可能需要将标签括在$中,就像这样:'${0:g}$'

与其改变刻度,不如改变单位?制作一个单独的x值数组X,其单位为nm。这样,当你绘制数据时,它已经是正确的格式了!只需确保添加一个xlabel来指示单位(无论如何都应该始终)。

from pylab import *

# Generate random test data in your range
N = 200
epsilon = 10**(-9.0)
X = epsilon*(50*random(N) + 1)
Y = random(N)

# X2 now has the "units" of nanometers by scaling X
X2 = (1/epsilon) * X

subplot(121)
scatter(X,Y)
xlim(epsilon,50*epsilon)
xlabel("meters")

subplot(122)
scatter(X2,Y)
xlim(1, 50)
xlabel("nanometers")

show()

enter image description here

要设置x轴的范围,可以使用set_xlim(left, right)here are the docs

更新:

看起来你想要一个相同的图,但是只需要改变“刻度值”,你可以通过获取刻度值,然后把它们改变成你想要的。所以为了满足你的需要

ticks = your_plot.get_xticks()*10**9
your_plot.set_xticklabels(ticks)

相关问题 更多 >