【问题标题】:How to format the twin logarithmic x axis tick labels to appear as powers of ten?如何格式化双对数 x 轴刻度标签以显示为 10 的幂?
【发布时间】:2016-03-26 20:38:18
【问题描述】:

我的两个 x 轴都是对数刻度。上 x 轴是下轴的函数(在本例中为平方)。

虽然下轴刻度标签会自动格式化为 10 的幂,但上轴有不同的默认格式(科学记数法):

我该如何解决这个问题?

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twiny()

x = np.logspace(-9,0,10)
x2 = x**2
new_tick_locations = x[3:-3]
new_tick_labels = x2[3:-3]
y = np.ones(np.size(x))

ax1.semilogx(x,y)
plt.grid(True)
ax1.set_xlabel(r"Original x-axis: $X$")

ax2.set_xscale('log')
ax2.set_xlim(ax1.get_xlim())
ax2.set_xticks(new_tick_locations)
ax2.set_xticklabels(new_tick_labels)
ax2.set_xlabel(r"Modified x-axis: $X^2$")
plt.show()

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    至少有两种方法可以解决这个问题:

    1. 在将new_tick_labels 分配到ax2.set_xticklabels() 之前格式化它们

    2. 使用FuncFormater进行单位转换和格式化,无需调用ax2.set_xticklabels()

    要采用第一种方式,您需要替换此行:

    ax2.set_xticklabels(new_tick_labels)
    

    用这个块:

    new_tick_labels = ['$\mathdefault{10^{%i}}$' % np.log10(l) 
                       for l in new_tick_labels]
    ax2.set_xticklabels(new_tick_labels)
    

    要从FuncFormater 中受益,请将同一行替换为:

    from matplotlib.ticker import FuncFormatter
    ax2.xaxis.set_major_formatter(
        FuncFormatter(lambda x, p: 
            '$\mathdefault{10^{%i}}$' % np.log10(x**2)))
    

    如果您使用FuncFormater,也可以删除new_tick_labels = x2[3:-3]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-28
      • 1970-01-01
      • 2017-03-16
      • 1970-01-01
      • 2021-06-01
      • 1970-01-01
      相关资源
      最近更新 更多