Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 无法在matplotlib.pyplot中设置双x轴上的标签格式_Python 3.x_Matplotlib_Formatting - Fatal编程技术网

Python 3.x 无法在matplotlib.pyplot中设置双x轴上的标签格式

Python 3.x 无法在matplotlib.pyplot中设置双x轴上的标签格式,python-3.x,matplotlib,formatting,Python 3.x,Matplotlib,Formatting,我想用双x轴绘制一个图形,并将上轴的标签格式化为科学符号 import numpy as np import matplotlib.pyplot as plt imp1=np.arange(0,2,2/50) imp1_pdf=np.arange(0,6,6/50) fig1=plt.figure() axs1=fig1.add_subplot(111) axs1.set_xlim(0,2) axs1.set_ylim(0,6.5) axs2 = axs1.twiny() axs1.pl

我想用双x轴绘制一个图形,并将上轴的标签格式化为科学符号

import numpy as np
import matplotlib.pyplot as plt

imp1=np.arange(0,2,2/50)
imp1_pdf=np.arange(0,6,6/50)

fig1=plt.figure()
axs1=fig1.add_subplot(111)
axs1.set_xlim(0,2)
axs1.set_ylim(0,6.5)

axs2 = axs1.twiny()

axs1.plot(imp1,imp1_pdf)

new_tick_locations=axs1.get_xticks()

axs2.set_xticks(new_tick_locations)
axs2.set_xticklabels(new_tick_locations/1000)
axs2.axes.ticklabel_format(axis='x',style='sci',scilimits=(0,0))

axs1.grid(b=True, which='major',linestyle='-')
fig1.tight_layout()
fig1.savefig('tickformat.png',dpi=600)
如果不使用ticklabel格式,该图如下所示:

但是,当我尝试格式化上x轴时,会出现如下错误:

AttributeError:此方法仅适用于ScalarFormatter

如果我使用另一种方法,也就是使用
FormatStrFormatter

from matplotlib.ticker import FormatStrFormatter

axs2.xaxis.set_major_formatter(FormatStrFormatter('%.1e'))
上x轴值将与下x轴值相同,如下所示:


有人能告诉我如何解决这个问题吗?

问题是您试图修改自定义标签,这些标签只是您定义的字符串
(new\u tick\u locations/1000)
。双轴上的实际值与下轴上的实际值相同。您只是在修改记号标签。完成任务的一种方法是使用
十进制
以科学的格式构造修改过的记号标签,然后将它们分配到上x轴。然后可以选择任何因子,而不是要显示的1000

import numpy as np
from decimal import Decimal
import matplotlib.pyplot as plt

imp1=np.arange(0,2,2/50)
imp1_pdf=np.arange(0,6,6/50)

fig1=plt.figure()
axs1=fig1.add_subplot(111)
axs1.set_xlim(0,2)
axs1.set_ylim(0,6.5)

axs2 = axs1.twiny()
axs1.plot(imp1,imp1_pdf)

new_tick_locations=axs1.get_xticks()
ticks = ['%.2E' % Decimal(i) for i in (new_tick_locations/1000)] # <-- make new ticks
axs2.set_xticks(new_tick_locations)
axs2.set_xticklabels(ticks, rotation = 45) # <-- assign new ticks and rotate them

axs1.grid(b=True, which='major',linestyle='-')
fig1.tight_layout()
将numpy导入为np
从十进制输入十进制
将matplotlib.pyplot作为plt导入
imp1=np.arange(0,2,2/50)
imp1_pdf=np.arange(0,6,6/50)
图1=plt.图()
axs1=图1.添加子批次(111)
axs1.set_xlim(0,2)
axs1.set_ylim(0,6.5)
axs2=axs1.twiny()
axs1.plot(imp1,imp1_pdf)
新建\u勾选\u位置=axs1.get\u xticks()

滴答声=['%.2E'%Decimal(i)表示(新的滴答声位置/1000)]#谢谢。太棒了!