简体   繁体   中英

Matplotlib doesn't plot certain data..although scatter works

say

twenty = [[0.00186157 0.00201416 0.00216675 0.00213623 0.00253296 0.00250244  0.00280762 0.00292969 0.00308228 0.0032959  0.00338745 0.003479  0.003479   0.00341797 0.00335693 0.00320435 0.00308228 0.0027771  0.00253296 0.00216675]]
twentyfirst = [[0.00186157]]

Following function - while it should plot for both scatter as well as lineplot, (this is implemented exactly as in the page ) Got as far as to plot both in markers, but the matplotlib is lost in generating lines.

def plot_time_series(twenty, twentyfirst):
    xlabel = np.arange(0, 1, 1./20).reshape(1,20)
    print(np.ones(twenty.shape[1])[np.newaxis,:].shape) #(1,20)
    A = np.vstack([xlabel, np.ones(twenty.shape[1])[np.newaxis,:]]).T

    m, c = np.linalg.lstsq(A, twenty.T)[0]
    print(m, c)
    plt.scatter(xlabel, twenty.T, c='b', label='data')
    ylabel = m*xlabel + c
    print(ylabel.shape) #(1,20)
    plt.plot(xlabel, ylabel, '-ok', label = 'fitted line')
    plt.legend(loc='best')
    plt.ylabel('amplitudes')
    plt.savefig('timeseries_problem2'+'_4')
    plt.close()

在此处输入图片说明

Under the hood, this question asks about the difference between plotting

plt.plot([[1,2,3]],[[2,3,1]])

and

plt.plot([[1],[2],[3]],[[2],[3],[1]])

In both cases the lists are 2 dimensional. In the first case, you have a single row of data. In the second case you have a single column of data.

From the documentation :

x , y : array-like or scalar
[...]
Commonly, these parameters are arrays of length N. However, scalars are supported as well (equivalent to an array with constant value).

The parameters can also be 2-dimensional . Then, the columns represent separate data sets .

The important part is the last sentence. If data is 2D, as here, it is interpreted column-wise. Since the row-array [[2,3,1]] consists of 3 columns, each with a single value. plot will hence produce 3 single "lines" with one point. But since a single point defines no line, it will only be visible when activating the marker, eg

plt.plot([[1,2,3]], [[2,3,1]], marker="o")

在此处输入图片说明

When transposing this row array to a column array, it will be interpreted as a single dataset with 3 entries. Hence the desired outcome of a single line

plt.plot([[1],[2],[3]], [[2],[3],[1]])

在此处输入图片说明

Of course flattening the array to 1D is equally possible,

plt.plot(np.array([[1,2,3]]).flatten(), np.array([[2,3,1]]).flatten())

You may easily check how many lines you produced

print(len(plt.plot([[1,2,3]],[[2,3,1]])))            # prints 3
print(len(plt.plot([[1],[2],[3]],[[2],[3],[1]])))    # prints 1

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