如何为Hexbin绘图的Colorbar创建自定义刻度和标签?
答案 0 :(得分:2)
修改颜色栏的关键是获取对它的访问权限,然后使用定位器和格式化程序(在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
(这个问题给我带来了一些重大问题,所以我想我会分享如何做到这一点。)