我想在 [0, 4] 中的區間 x 上繪制點。我的函式對非常小的值執行一些有趣的操作,因此我想創建一個非線性比例,該比例將為較小的 x 值使用更多空間。對數刻度將是一個很好的解決方案,但問題是我的 x 軸必須包含 0,這不是對數軸的一部分。
所以我考慮使用功率等級。經過一番谷歌搜索后,我遇到了以下解決方案。
def stratify(ax, power=2):
f = lambda x: (x 1)**(1 / power)
f_inv = lambda y: y**power - 1
ax.set_xscale('function', functions=(f, f_inv))
x = np.linspace(0, 4, 100)
y = np.sqrt(x)
fig, ax = plt.subplots()
ax.plot(x, y)
stratify(ax, 2)
plt.show()
該函式stratify將繪圖的 x 尺度更改為平方根函式。這看起來有點正確。下面是對應于上述代碼的最小示例圖(不是實際資料)。

我想控制 x 尺度中的非線性,這就是我引入power引數的原因。但是,當我將功率引數更改為與 2 不同的值時,繪圖根本沒有改變。這對我來說非常令人驚訝。如果有人能建議我如何控制 x 軸的非線性程度,我將不勝感激。如果可能,我希望它更加非線性,使區間 [0, 0.5] 占據圖的一半。
編輯雖然@Thomas 當前的解決方案按預期作業,但當人們試圖用它做任何事情時,繪圖例程會拋出很多錯誤。例如,我想插入額外的刻度,因為無論出于何種原因,原始刻度都只有整數刻度。通過插入額外的刻度會ax.set_xticks(ax.get_xticks() [0.5])導致錯誤posx and posy should be finite values。這是什么錯誤,如何繞過?
uj5u.com熱心網友回復:
對我來說,從 切換power=2到時會發生變化power=10。請小心在正確的位置編輯它,即在呼叫stratify=X.
這里是power=2:
這里是power=10:

但是,這是另一個稍微激進的建議:
import numpy as np
import matplotlib.pyplot as plt
def stratify(ax, scale=1):
f = lambda x: np.log(x / scale 1)
f_inv = lambda y: scale * (np.exp(y) - 1)
ax.set_xscale('function', functions=(f, f_inv))
x = np.linspace(0, 4, 100)
y = np.sqrt(x)
fig, axs = plt.subplots(1, 3)
for i, scale in enumerate([10,1,0.1]):
ax = axs[i]
ax.set_title(f'Scale={scale}')
ax.plot(x, y)
stratify(ax, scale=scale)
plt.show()
導致

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/354227.html
標籤:Python matplotlib
