【问题标题】:Colorbar tick values and labels do not match颜色条刻度值和标签不匹配
【发布时间】:2022-01-28 06:07:33
【问题描述】:

我的代码

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 的次要刻度除外)。

知道发生了什么吗?提前谢谢!

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    默认情况下,等高线图的颜色条刻度是均匀分布的(每种颜色的距离相同)。您可以将其更改为 spacing='proportional' 以使每种颜色使用其相应比例的颜色条。

    (使用color='white' 而不是tick_params 中的colors=...,只会更改刻度本身的颜色,而不更改刻度标签。)

    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()
    

    【讨论】:

    • 哇,我明白了,非常感谢!文档中提到了吗?这不是应该修复的错误吗?我认为我的代码中没有任何可疑的行会导致刻度值和标签不正确匹配..
    • 默认颜色条有spacing='uniform'。哪个是首选取决于许多因素。
    • 感谢您提供有关 color 而不是 colors 的详细信息。很抱歉错过了direction='in' ;)
    猜你喜欢
    • 1970-01-01
    • 2016-06-14
    • 2020-02-18
    • 1970-01-01
    • 2018-10-06
    • 1970-01-01
    • 2016-02-19
    • 1970-01-01
    • 2020-01-05
    相关资源
    最近更新 更多