简体   繁体   中英

Matplotlib automatic axis gives unexpected result

I'm plotting some data with Matplotlib but the auto axis labels are off. The X axis has negative values in the label where they should be positive and the Y axis has a very strange scale.

Here's some code:

import numpy as np
import numpy.polynomial.polynomial as poly
import matplotlib.pylab as plot

# pass in same sized arrays x, y, and z, returns fit of x to z and y to z 
def fitData(x, y, z): 
    x_coefs = poly.polyfit(x, z, 1)
    xfit = poly.Polynomial(x_coefs)    # instead of np.poly1d
    y_coefs = poly.polyfit(y, z, 3)
    yfit = poly.Polynomial(y_coefs)    # instead of np.poly1d
    return xfit, yfit 

x = [3.08,  3.1 ,  3.12,  3.14,  3.16,  3.18,  3.2 ,  3.22,  3.24, 
     3.26,  3.28,  3.3 ,  3.32,  3.34,  3.36,  3.38,  3.4 ,  3.42, 
     3.44,  3.46,  3.48,  3.5 ,  3.52,  3.54,  3.56,  3.58,  3.6 , 
     3.62,  3.64,  3.66,  3.68]

y = [0.000857,  0.001182,  0.001619,  0.002113,  0.002702,  0.003351,
    0.004062,  0.004754,  0.00546 ,  0.006183,  0.006816,  0.007362,
    0.007844,  0.008207,  0.008474,  0.008541,  0.008539,  0.008445,
    0.008251,  0.007974,  0.007608,  0.007193,  0.006752,  0.006269,
    0.005799,  0.005302,  0.004822,  0.004339,  0.00391 ,  0.003481,
    0.003095]

z = np.linspace(0, 1, num=len(x)) # create as many z points as input data 

xfit, yfit = fitData(x, y, z)

ax1 = plot.subplot(1, 2, 1)
plot.title("X position")
plot.xlabel("Z (ft)")
plot.ylabel("X (ft)")
ax1.plot(z, xfit(z))

ax2 = plot.subplot(1, 2, 2)
plot.title("Y position")
plot.xlabel("Z (ft)")
plot.ylabel("Y (ft)")
ax2.plot(z, yfit(z))

plot.tight_layout()
plot.show() 

And here are my resultant plots:

在此处输入图片说明

As you can see, the range on the X plot scale bar seems to run reverse, and the y plot scale is way off. Does anyone have any idea why this might be happening?

In general I assume Matplotlib knows the range of your data, so I'd start by looking at the data it is plotting. Looking at the x data, the y-intercept should be 3.08, while x_coefs is array([-5.13333333, 1.66666667] so your fit functions are off somehow (ipython or print(x_coefs) is your friend here).

You need to reverse x and z in x_coefs = poly.polyfit(x, z, 1) , similarly for y_coefs .

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