简体   繁体   中英

How to set the ticks of log scale for x&y axis?

I want to plot a log scale graph without scientific notation.

    import matplotlib as mpl
    import matplotlib.pyplot as plt

    plt.plot(np.arange(0,10,0.1))

    plt.xscale('log')
    plt.yscale('log')
    plt.xlim(0.1,100)
    plt.ylim(1,10)

    plt.gca().xaxis.set_major_formatter(mpl.ticker.ScalarFormatter())
    plt.gca().yaxis.set_major_formatter(mpl.ticker.ScalarFormatter())
    plt.show()

Question:

  1. Y axis still shows the format of scientific notation. How to change it?

  2. How to make specific ticks for y axis? I tried plt.yticks([1,10]) , but it doesn't work.

  3. How to get rid of the decimal point of ticks for both x and y axis?

    在此输入图像描述

1. Get rid of Scientific notation.

The ticks are major and minor ticks, hence you would need to set the minor formatter as well:

plt.gca().yaxis.set_major_formatter(mpl.ticker.ScalarFormatter())
plt.gca().yaxis.set_minor_formatter(mpl.ticker.ScalarFormatter())

2. Show ticks at specific custom locations

Getting rid of the minor ticklabels allows yticks to work as expected.

plt.yticks([1,10])
plt.gca().yaxis.set_minor_formatter(mpl.ticker.NullFormatter())

3. Getting rid of the decimal points

I suppose it does not make sense to get rid of the decimal points for a label like 0.1 . Hence one would probably choose a StrMethodFormatter with the g eneral purpose numeric format g .

plt.gca().yaxis.set_major_formatter(mpl.ticker.StrMethodFormatter("{x:g}"))
  1. Use plt.ticklabel_format(style='plain') to get rid of the scientific notation.

  2. It looks like plt.yticks([1,10]) did its job. yticks() only adds the specific numbers you provide, not a range. So the ticks that it added were at y=1 and y=10, which are exactly at the bottom and top edges of your graph. If you want to have more ticks between those, you can try plt.yticks(np.arange(1,10, step=d)) where 'd' is the distance you want between each step.

  3. Try plt.gca().xaxis.set_major_formatter(mpl.ticker.EngFormatter(places=0)) to get rid of the decimal points.

All this can be found in the matplotlib docs, though admittedly it takes some digging.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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