2012-04-16 21 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