我的代碼:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
fig, ax = plt.subplots()
contour_levels = [10,100,500,1000,10000]
h = np.histogram2d(np.random.normal(0,2,10000),np.random.normal(0,2,10000),bins=10)
c = ax.contourf(h[0].T,cmap='magma',norm=LogNorm(),levels=contour_levels,extend='both')
cbar = plt.colorbar(c)
ticks = cbar.ax.yaxis.get_ticklabels()
cbar.ax.tick_params(which='minor',size=8,width=1,colors='white')
cbar.ax.tick_params(which='major',size=15,width=1,colors='white')
[t.set_color('black') for t in ticks]
ax.set_aspect('equal')
plt.show()
結果:

>print(ticks)
[Text(1, 10.0, '$\\mathdefault{10^{1}}$'),
Text(1, 56.234132519034915, '$\\mathdefault{10^{2}}$'),
Text(1, 316.2277660168379, ''),
Text(1, 1778.2794100389228, '$\\mathdefault{10^{3}}$'),
Text(1, 10000.0, '$\\mathdefault{10^{4}}$')]
問題:
非常令人震驚的是,顏色條刻度標簽僅匹配第一個和最后一個刻度上的相應刻度值!次要刻度的奇怪位置暗示主要刻度標簽被錯誤放置(導致 10^4 的次要刻度除外)。
知道發生了什么嗎?先感謝您!
uj5u.com熱心網友回復:
默認情況下,等高線圖的顏色條刻度是均勻分布的(每種顏色的距離相同)。您可以將其更改spacing='proportional'為讓每種顏色使用其對應的顏色條比例。
(使用color='white'而不是colors=...在 中tick_params,僅更改刻度本身的顏色,而不更改刻度標簽。)
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
import numpy as np
fig, ax = plt.subplots()
contour_levels = [10, 100, 500, 1000, 10000]
h, xedges, yedges = np.histogram2d(np.random.normal(0, 2, 10000), np.random.normal(0, 2, 10000), bins=10)
h[h == 0] = np.nan
cont = ax.contourf((xedges[:-1] xedges[1:]) / 2, (yedges[:-1] yedges[1:]) / 2, h.T, cmap='magma', norm=LogNorm(),
levels=contour_levels, extend='both')
cbar = plt.colorbar(cont, ticks=contour_levels, format='%.0f', spacing='proportional')
ticks = cbar.ax.yaxis.get_ticklabels()
cbar.ax.tick_params(which='minor', size=8, width=1, color='white', direction='in')
cbar.ax.tick_params(which='major', size=15, width=1, color='white', direction='in')
ax.set_aspect('equal')
plt.show()

轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/398882.html
標籤:Python matplotlib
上一篇:具有自定義資料的3D繪圖表面
下一篇:默認Matplotlib軸子項
