kinder chen
kinder chen

Reputation: 1461

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?

    enter image description here

Upvotes: 5

Views: 3583

Answers (2)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339052

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 general purpose numeric format g.

plt.gca().yaxis.set_major_formatter(mpl.ticker.StrMethodFormatter("{x:g}"))

Upvotes: 3

Nick Porter
Nick Porter

Reputation: 173

  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.

Upvotes: 1

Related Questions