如何格式化双对数x轴刻度标签显示为10的幂?

2024-05-19 08:10:52 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

enter image description here

我怎么解决这个问题?在

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()

Tags: importnewlabelsasnpfigpltx2
1条回答
网友
1楼 · 发布于 2024-05-19 08:10:52

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

  1. ax2.set_xticklabels()中分配它们之前,请格式化您的new_tick_labels

  2. 使用FuncFormater可以同时进行单位转换和格式化,而不需要调用ax2.set_xticklabels()

要想走第一条路,您需要替换这条线路:

ax2.set_xticklabels(new_tick_labels)

使用此块:

^{pr2}$

要从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]。在

相关问题 更多 >

    热门问题