How to Remove Relative Shift in Matplotlib Axis

How to remove relative shift in matplotlib axis

plot([1000, 1001, 1002], [1, 2, 3])
gca().get_xaxis().get_major_formatter().set_useOffset(False)
draw()

This grabs the current axes, gets the x-axis axis object and then the major formatter object and sets useOffset to false (doc).

In newer versions (1.4+) of matplotlib the default behavior can be changed via the axes.formatter.useoffset rcparam.

Matplotlib not giving the correct graph of a function

In fact, it seems to me that you have a correct answer but I think that you didn't realize the y-scale. If you see the top of Y axis, there is 1e-6+2.6250000000e-1, this means that the value that you have on the Y axis you have to multiply by 1e-6 ( i.e. 10^-6) and sum 2.6250000000e-1 ( i.e. 0.2625). So, v(0)=0*(10^-6) + 0.2625 =0.2625.

Odd Axis-Offset

It looks like normal behavior to me, if you dont want an offset you can disable it with:

fig, ax = plt.subplots()

ax.plot([680e-3 - 20.0, 720e-3 - 20.0])

ax.yaxis.set_major_formatter(mpl.ticker.ScalarFormatter(useOffset=False))

Sample Image

You can also set the offset yourself with:

mpl.ticker.ScalarFormatter(useOffset=-20)

Reduce left and right margins in matplotlib plot

One way to automatically do this is the bbox_inches='tight' kwarg to plt.savefig.

E.g.

import matplotlib.pyplot as plt
import numpy as np
data = np.arange(3000).reshape((100,30))
plt.imshow(data)
plt.savefig('test.png', bbox_inches='tight')

Another way is to use fig.tight_layout()

import matplotlib.pyplot as plt
import numpy as np

xs = np.linspace(0, 1, 20); ys = np.sin(xs)

fig = plt.figure()
axes = fig.add_subplot(1,1,1)
axes.plot(xs, ys)

# This should be called after all axes have been added
fig.tight_layout()
fig.savefig('test.png')

Shift plots of different lengths in the same x-axis

From the set up of the question I am going to assume that the the x-values do not have any numerical meaning so it is safe from a data-point-of-view to shift them around. Instead of plotting your data against range(len(...)), do the shift there!

import matpoltlib.pyplot as plt
import numpy as np

def synthetic_data(length):
"make some variable length synthetic data to plot."
return np.exp(-((np.linspace(-5, 5, length)) ** 2))

data = [synthetic_data(51), synthetic_data(75), synthetic_data(105)]

fig, ax = plt.subplots(constrained_layout=True)

for d in data:
x_vector = np.arange(len(d)) - len(d) // 2
ax.plot(x_vector, d)

ax.axvline(0, color="k", ls="--")
ax.set_xlabel("delta from center")
ax.set_ylabel("synthetic data!")

shifted curves



Related Topics



Leave a reply



Submit