This question already has answers here:
Matplotlib log scale tick label number formatting
                                
                                    (4个答案)
                                
                        
                                在10个月前关闭。
            
                    
我想使用ticklabel_format(style='plain')来抑制对数轴上的科学计数法,但根据行的顺序,它要么被忽略(第一图),要么抛出异常(第三图,下面显示错误)。但是,它适用于线性轴(第二个图)。

Matplotlib的1.5.12.2.2版本均会发生这种情况。

问题:为什么对对数轴它会忽略或失败,而对线性轴却能正常工作?



Traceback (most recent call last):
File "test.py", line 25, in <module>
ax3.ticklabel_format(style='plain', axis='x')
File "/Users/david/anaconda2/lib/python2.7/site-packages/matplotlib/axes/_base.py", line 2805, in ticklabel_format
"This method only works with the ScalarFormatter.")
AttributeError: This method only works with the ScalarFormatter.


这是情节:

python - Matplotlib的ticklabel_format(style =&#39;plain&#39;)被忽略或对数轴失败,但对线性轴有效-LMLPHP

import numpy as np
import matplotlib.pyplot as plt

x = np.logspace(-3, 3, 19)
y = np.log10(x)

fig = plt.figure()

ax1 = fig.add_subplot(3, 1, 1)
ax1.plot(x, y)
ax1.set_title("style='plain' is ignored", fontsize=16)
ax1.ticklabel_format(style='plain', axis='x')
ax1.set_xscale('log')

ax2 = fig.add_subplot(3, 1, 2)
ax2.plot(x, y)
ax2.set_title("style='plain' works", fontsize=16)
ax2.ticklabel_format(style='plain', axis='x')

if True:
    ax3 = fig.add_subplot(3, 1, 3)
    ax3.plot(x, y)
    ax3.set_title('THIS FAILS', fontsize=16)
    ax3.set_xscale('log')
    ax3.ticklabel_format(style='plain', axis='x')

plt.show()

最佳答案

我不明白为什么对线性轴关闭了科学记号,为什么对对数轴只忽略了科学记数法或仅对对数轴抛出异常,但是基于this answer,我至少可以阻止不良行为。

对于问题中的三个案例为什么会产生不同的行为,我仍在等待答案。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter

x = np.logspace(-3, 3, 19)
y = np.log10(x)

fig = plt.figure()

ax1 = fig.add_subplot(3, 1, 1)
ax1.plot(x, y)
ax1.set_title("style='plain' is ignored", fontsize=16)
ax1.ticklabel_format(style='plain', axis='x')
ax1.set_xscale('log')

ax2 = fig.add_subplot(3, 1, 2)
ax2.plot(x, y)
ax2.set_title("style='plain' works", fontsize=16)
ax2.ticklabel_format(style='plain', axis='x')

if True:
    ax3 = fig.add_subplot(3, 1, 3)
    ax3.plot(x, y)
    ax3.set_title('This now works!', fontsize=16)
    ax3.set_xscale('log')
    formatter = FuncFormatter(lambda y, _: '{:.16g}'.format(y)) # https://stackoverflow.com/a/49306588/3904031
    ax3.xaxis.set_major_formatter(formatter)

plt.show()


python - Matplotlib的ticklabel_format(style =&#39;plain&#39;)被忽略或对数轴失败,但对线性轴有效-LMLPHP

关于python - Matplotlib的ticklabel_format(style ='plain')被忽略或对数轴失败,但对线性轴有效,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55826888/

10-10 11:20