2012-04-16 67 views
21

我正在python中创建绘图。有没有办法通过一个因子重新定标轴? yscalexscale命令只允许我关闭对数刻度。在matplotlib中更改绘图比例因子

编辑:
例如,如果我有一个从1纳米到50纳米的标度图,x标度范围将从1×10 ^( - 9)到50×10 ^( - 9),我希望它从1变为50.因此,我想要的情节功能10来划分放置在图中的x值^( - 9)

+4

Yotam,你似乎有很多已回答的问题,但你还没有接受答案。请接受老问题的答案或添加其他信息,以便我们可以帮助您! – Hooked 2012-04-16 14:08:09

回答

10

而不是改变蜱,为什么不改变单位呢?制作单位为nm的x值的单独阵列X。这样,当你绘制数据时,它已经处于正确的格式!只要确保你添加了一个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

+0

这就是我现在想要做的。我认为有更优雅的方式。 – Yotam 2012-04-17 06:17:20

5

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

更新:

它看起来像你想要一个相同的情节,但只是改变'刻度值',你可以通过获取刻度值然后将其改变为任何你想要的。因此,对于您的需要,它会是这样的:

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

据我了解,xlim更改了绘图的范围,并没有对其进行缩放。看我的例子。 – Yotam 2012-04-16 11:39:25

+0

@Yotam - 所以你想要的情节是相同的,但在x刻度标签上的值会改变? – fraxel 2012-04-16 11:48:35

+0

令人惊讶的简单解决方案。但是,我发现这会导致带小数的标签,即使使用仅应显示整数的报价器(例如MultipleLocator或MaxNLocator)。我发现这可以通过使用'ticks.astype(int)'而不是'ticks'来解决。 – 2017-10-07 14:33:18

40

正如您已经注意到,xscaleyscale不支持简单的线性重新缩放(不幸)。作为替代带钩的答案,而不是与数据搞乱,你可以欺骗的标签,就像这样:

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因为我有,你可能要封闭LA贝尔斯在$,像这样:'${0:g}$'

+0

这可能是更正确的答案。谢谢@oystein – oche 2016-03-26 00:20:55

+0

这就是我们需要的破解 – 2017-08-06 10:00:23