Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
555 views
in Technique[技术] by (71.8m points)

python - Plotting with scientific axis, changing the number of significant figures

I am making the following plot in matplotlib, using amongst other things plt.ticklabel_format(axis='y',style='sci',scilimits=(0,3)). This yields a y-axis as so:

enter image description here

Now the problem is that I want the y-axis to have ticks from [0, -2, -4, -6, -8, -12]. I have played around with the scilimits but to no avail.

How can one force the ticks to only have one significant figure and no trailing zeros, and be floats when required?

MWE added below:

import matplotlib.pyplot as plt
import numpy as np

t = np.arange(0.0, 10000.0, 10.)
s = np.sin(np.pi*t)*np.exp(-t*0.0001)

fig, ax = plt.subplots()

ax.tick_params(axis='both', which='major')
plt.ticklabel_format(style='sci', axis='x', scilimits=(0,3))
plt.plot(t,s)

plt.show()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When I ran into this problem, the best I could come up with was to use a custom FuncFormatter for the ticks. However, I found no way to make it display the scale (e.g. 1e5) along with the axis. The easy solution was to manually include it with the tick label.

Sorry if this does not fully answer the question, but it may suffice as a relatively simple solution to the problem :)

In the MWE my solution looks somewhat like this:

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


def tickformat(x):
    if int(x) == float(x):
        return str(int(x))
    else:
        return str(x)        


t = np.arange(0.0, 10000.0, 10.)
s = np.sin(np.pi*t)*np.exp(-t*0.0001)

fig, ax = plt.subplots()

ax.tick_params(axis='both', which='major')
plt.plot(t,s)

fmt = FuncFormatter(lambda x, pos: tickformat(x / 1e3))
ax.xaxis.set_major_formatter(fmt)

plt.xlabel('time ($s 10^3$)')

plt.show()

Note that the example manipulates the x-axis!

enter image description here

Of course, this could be achieved even simpler by re-scaling the data. However, I assume you don't want to touch the data and only manipulate the axis.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...