首页 > 解决方案 > Pandas/Matplotlib 中 Hexbin 颜色条的自定义刻度和标签

问题描述

如何为 Hexbin 图的颜色条创建自定义刻度和标签?

标签: pandasmatplotlibplotcolorbar

解决方案


修改颜色条的关键是获得对它的访问权限,然后使用定位器和格式化程序(在matplotlib.ticker中)来修改它们,最后在更改完成后更新刻度。

import matplotlib.pyplot as plt
import matplotlib.ticker as tkr 

# set the values of the main y axis and colorbar ticks 
ticklocs = tkr.FixedLocator( np.linspace( ymin, ymax, ystep ) )
ticklocs2 = tkr.FixedLocator( np.arange( zmin, zmax, zstep ) )

# set the label format for the main y axis, and colorbar
tickfrmt = tkr.StrMethodFormatter( yaxis_format )
tickfrmt2 = tkr.StrMethodFormatter( zaxis_format )

# must save a reference to the plot in order to retrieve its colorbar
hb = df.plot.hexbin(
    'xaxis', 'yaxis', C = 'zaxis',
    sharex = False
)

# get plot axes, ax[0] is main axes, ax[1] is colorbar
ax = plt.gcf().get_axes() 

# get colorbar
cbar = hb.collections[ 0 ].colorbar

# set main y axis ticks and labels
ax[ 0 ].yaxis.set_major_locator( ticklocs )
ax[ 0 ].yaxis.set_major_formatter( tickfrmt )

# set color bar ticks and labels
cbar.locator = ticklocs2 
cbar.formatter = tickfrmt2
cbar.update_ticks() # update ticks for changes to take place

(这个问题给我带来了一些重大问题,所以我想我会分享如何完成这个。)


推荐阅读