【问题标题】:Custom Ticks and Labels for Hexbin Colorbar in Pandas/MatplotlibPandas/Matplotlib 中 Hexbin 颜色条的自定义刻度和标签
【发布时间】:2018-04-27 16:05:44
【问题描述】:

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

【问题讨论】:

    标签: pandas matplotlib plot colorbar


    【解决方案1】:

    修改颜色条的关键是访问它,然后使用定位器和格式化程序(在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
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-06
      • 2016-06-14
      • 2020-02-18
      • 1970-01-01
      • 1970-01-01
      • 2020-01-05
      • 2020-09-28
      • 2016-02-19
      相关资源
      最近更新 更多