我已經嘗試解決這個問題好幾天了,但我在網上找到的所有解決方案似乎都不適合我,盡管問題看起來很簡單。
import numpy as np
from matplotlib import pyplot as plt
grid_x = np.linspace(-5, 5, 500)
grid_y = np.linspace(-5, 5, 500)
xx, yy = np.meshgrid(grid_x, grid_y)
fig, ax = plt.subplots(2)
rand1 = np.ones((500,500))
rand1[:, 250:] = 2
ax[0].contourf(xx, yy, rand1, alpha=.3, cmap = 'jet')
rand2 = np.zeros((500,500))
rand2[:, 200:250] = 1
rand2[:,250:] = 2
ax[1].contourf(xx, yy, rand2, alpha=.3, cmap = 'jet')
這是通過運行上面的結果圖:

在第一個軸上,1s 映射到藍色,2s 映射到紅色。在第二個軸上,0 映射到藍色,1 映射到綠色,2 映射到紅色。
我希望它保持一致,例如,1s 總是映射到藍色,2s 總是映射到紅色,0s 總是映射到綠色。
據我所知,這個問題將通過確保兩個圖都在 (0,1,2) 中的值都出現在某個時候來解決,但是我不能確保我的專案,所以這不是一個有效的解決方案.
我的另一個想法是分別映射每個區域。但是,我不確定如何執行此操作,盡管我認為對于上面的簡單示例會相對容易,但我需要將其推廣到任何形狀任意的子區域。
有沒有人有關于如何解決這個問題的建議?非常感謝!
uj5u.com熱心網友回復:
為了更好地了解正在發生的事情,添加顏色條會有所幫助。它顯示了使用的級別和相應的顏色。
要使相應級別具有相同的顏色,圖之間的級別應相同:
import numpy as np
from matplotlib import pyplot as plt
grid_x = np.linspace(-5, 5, 500)
grid_y = np.linspace(-5, 5, 500)
xx, yy = np.meshgrid(grid_x, grid_y)
rand1 = np.ones((500, 500))
rand1[:, 250:] = 2
rand2 = np.zeros((500, 500))
rand2[:, 200:250] = 1
rand2[:, 250:] = 2
# common_levels = np.linspace(0, 2, 11)
common_levels = np.linspace(min(rand1.min(), rand2.min()), max(rand1.max(), rand2.max()), 11)
fig, axs = plt.subplots(ncols=2, nrows=2, figsize=(12, 6))
contour00 = axs[0, 0].contourf(xx, yy, rand1, alpha=.3, cmap='jet')
axs[0, 0].set_title('values 1 and 2, default levels')
plt.colorbar(contour00, ax=axs[0, 0])
contour01 = axs[0, 1].contourf(xx, yy, rand1, levels=common_levels, alpha=.3, cmap='jet')
plt.colorbar(contour01, ax=axs[0, 1])
axs[0, 1].set_title('values 1 and 2, common levels')
contour10 = axs[1, 0].contourf(xx, yy, rand2, alpha=.3, cmap='jet')
axs[1, 0].set_title('values 0, 1 and 2, default levels')
plt.colorbar(contour10, ax=axs[1, 0])
contour11 = axs[1, 1].contourf(xx, yy, rand2, levels=common_levels, alpha=.3, cmap='jet')
axs[1, 1].set_title('values 0, 1 and 2, common levels')
plt.colorbar(contour11, ax=axs[1, 1])
plt.tight_layout()
plt.show()

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