【问题标题】:Hexadecimal X-axis in matplotlib?matplotlib中的十六进制X轴?
【发布时间】:2014-02-07 00:20:18
【问题描述】:

是否有可能以某种方式在 matplotlib 中以十六进制表示法打印 X 轴上的值?对于我的绘图,X 轴代表内存地址。

谢谢。

【问题讨论】:

    标签: python matplotlib hex


    【解决方案1】:

    您可以在轴上设置一个格式化程序,例如FormatStrFormatter

    简单示例:

    import matplotlib.pyplot as plt
    import matplotlib.ticker as ticker
    
    
    plt.plot([10, 20, 30], [1, 3, 2])
    axes = plt.gca()
    axes.get_xaxis().set_major_locator(ticker.MultipleLocator(1))
    axes.get_xaxis().set_major_formatter(ticker.FormatStrFormatter("%x"))
    plt.show()
    

    【讨论】:

      【解决方案2】:

      在 64 位机器上使用 python 3.5 由于类型不匹配而出现错误。

      TypeError: %x format: an integer is required, not numpy.float64
      

      我通过使用函数格式化程序来解决它,以便能够转换为整数。

      import matplotlib.pyplot as plt
      import matplotlib.ticker as ticker
      
      def to_hex(x, pos):
          return '%x' % int(x)
      
      fmt = ticker.FuncFormatter(to_hex)
      
      plt.plot([10, 20, 30], [1, 3, 2])
      axes = plt.gca()
      axes.get_xaxis().set_major_locator(ticker.MultipleLocator(1))
      axes.get_xaxis().set_major_formatter(fmt)
      plt.show()
      

      【讨论】:

      • 这有多精确?
      【解决方案3】:

      另一种方法是:

      import matplotlib.pyplot as plt
      
      # Just some 'random' data
      x = sorted([489465, 49498, 5146, 4894, 64984, 465])
      y = list(range(len(x)))
      
      fig = plt.figure(figsize=(16, 4.5))
      ax = fig.gca()
      plt.plot(x, y, marker='o')
      
      # Create labels
      xlabels = map(lambda t: '0x%08X' % int(t), ax.get_xticks())    
      ax.set_xticklabels(xlabels);
      

      结果:

      【讨论】:

        猜你喜欢
        • 2011-12-09
        • 2011-06-01
        • 1970-01-01
        • 2018-07-26
        • 2014-08-24
        • 2020-09-25
        • 2023-03-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多