簡體   English   中英

通過 matplotlib 中的一個因子更改繪圖比例

[英]Changing plot scale by a factor in matplotlib

我正在用 python 創建一個情節。 有沒有辦法按一個因子重新縮放軸? yscalexscale命令只允許我關閉對數縮放。

編輯:
例如。 如果我有一個x尺度從 1 nm 到 50 nm 的圖,x 尺度的范圍將從 1x10^(-9) 到 50x10^(-9),我希望它從 1 變為 50。因此,我希望繪圖函數將放置在繪圖上的 x 值除以 10^(-9)

正如您所注意到的, 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() 

最后我有一張圖片的學分:

左:ax1 無縮放,右:ax2 y 軸縮放到千,x 軸縮放到納米

請注意,如果您有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()

在此處輸入圖片說明

要設置 x 軸的范圍,您可以使用set_xlim(left, right)這里是文檔

更新:

看起來您想要一個相同的圖,但只更改“刻度值”,您可以通過獲取刻度值然后將它們更改為您想要的任何值來實現。 所以對於你的需要,它會是這樣的:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM