繁体   English   中英

同一轴上刻度的不同格式

[英]Different format of ticks on the same axis

我想知道是否有一种方法可以使轴上的刻度标签具有不同的格式。在下面的代码中,我尝试了两种选择,第一种可行,但是y标签对于我的图形尺寸来说太大(我无法更改) ,第二个选项是我尝试一次更改刻度标签的格式,但结果是什么也没有显示,所以我的问题是要知道是否有解决方法。 谢谢

PS:第一次使用matplotlib绘制图形

   import matplotlib.pyplot as plt
   from matplotlib.ticker import AutoMinorLocator
   from matplotlib.ticker import LogLocator
   import matplotlib.ticker as mtick
   fig, ax = plt.subplots()

   #Define only minor ticks
   minorLocator = LogLocator(base=10,subs='auto')

   #Set the scale as a logarithmic one
   ax.set_xscale('log')
   ax.set_yscale('log')

   ax.set_ylim(0.00001,1000)

   #Set the minor ticks
   ax.xaxis.set_minor_locator(minorLocator)
   ax.yaxis.set_minor_locator(minorLocator)

   vals = ax.get_xticks()
   ax.set_xticklabels(['{:3.2f}'.format(x) for x in vals])    


   '''This line below if uncommented works, but the format is not 
   correct and only 7 characters are displayedMy y values will be 
   1000.00000, 100.00000,10.0000, 1.00000, 0.10000, 
   etc..        '''
   #ax.yaxis.set_major_formatter(mtick.PercentFormatter(decimals=5)) 


   ''' With the lines of code below which does not work, I am trying to have 
   the axis as 1000.00, 100.00, 10.00, 1.00, 0.1, 0.01, 0.001, 0.0001, etc.. 
   Nothing however is displayed'''
   vals = ax.get_yticks()
   for x in vals:
      if x > 0.001:
           ax.set_yticklabels(['{:7.2f}%'.format(x*1)])
      else:
           ax.set_yticklabels(['{:7.5f}%'.format(x*1)])

在第二个选项中,您需要将列表与所有标签以所需的格式传递给set_yticklabels ,而不是一个一个地传递。 列表理解应该起作用:

vals = ax.get_yticks()
ax.set_yticklabels(['{:7.2f}%'.format(x*1) if x > 0.001 else '{:7.5f}%'.format(x*1) for x in vals])

在此处输入图片说明

创建一个将以正确格式返回字符串的函数,然后使用matplotlib.ticker.FuncFormatter将您的函数指定为y轴格式化程序。 假设您希望y轴标签如下所示: 1000.00, 100.00, 10.00, 1.00, 0.1, 0.01, 0.001, 0.0001并改编自matplotlib示例

import math
from matplotlib.ticker import FuncFormatter

y_s = [1000, 100, 10, 1, 0.1000, 0.01000, 0.001000, 0.0001000]
x_s = [pow(10,y) for y in range(8)]

def my_format(y, pos):
    # y <= 0 formats not needed for log scale axis
    # use the log of the label to determine width and precision
    decades = int(math.log10(y))
    if decades >= 0:
        decimal_places = 2
        width = 1 + decades + decimal_places
    else:
        decimal_places = abs(decades)
        width = 1 + decimal_places
    # construct a format spec
    fmt = '{{:{}.{}f}}%'.format(width,decimal_places)
    return fmt.format(y)

fig, ax = plt.subplots()
ax.set_xscale('log')
ax.set_yscale('log')
##ax.set_ylim(min(y_s)/10,max(y_s)*10)
ax.set_ylim(0.00001,1000)
ax.yaxis.set_major_formatter(formatter)
plt.plot(x_s,y_s)
plt.show()
plt.close()

YAxis格式

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM