1

I'm using python3.X.

I came across some very strange behavior in matplotlib on a numpy matrix element as an ilustration I wanted to plot a simple sinc() function:

import numpy as np
import matplotlib.pyplot as plt

t=np.matrix(np.linspace(-10,10,1024))
x=np.sinc(t)

plt.plot(t,x,color='blue', linestyle='solid', linewidth=2)
plt.show()

The above piece of code generates: empty figure - STRANGE

While replacing the plt.plot(...) with:

plt.plot(t,x,'-ob')

generates:

desired result with 'o'

I could not figure out the reason for this behavior, would appreciate some help

3
  • In your 1st case plt.plot is interpreting your input as 1024 data sets and plotting each of them individually. Replace with t.T and x.T ( transpose your arrays) and it works fine Commented Sep 19, 2019 at 9:58
  • The same is true for your 2nd case, but since you are using dots rather than lines the output looks Ok. Commented Sep 19, 2019 at 9:59
  • @Brenlla can you post it as answer, for me to accept, Thanks Commented Sep 19, 2019 at 10:00

1 Answer 1

2

According to the docs, when using 2-D arrays, plot interprets the columns as separate data sets. Therefore, in your 1st case you are plotting 1024 lines with one point each. Since line plots work by drawing lines between points, nothing is being displayed:

t=np.matrix(np.linspace(-10,10,1024))
x=np.sinc(t)

plt.plot(t,x,color='blue', linestyle='solid', linewidth=2)
# plot shows nothing

Transpose your arrays to single column and it works fine:

plt.plot(t.T,x.T,color='blue', linestyle='solid', linewidth=2)
# plot shows line

The 2nd case works fine because when plotting dots, one is drawn for each data point. It is probably still faster to just plot one data set though:

plt.plot(t.T,x.T,'-ob')
# same output, probably faster
Sign up to request clarification or add additional context in comments.

3 Comments

Another question, why when i change t to np.array it works without the transpose; what is the essential difference between the 2 types?; Also would appreciate an upvote
It is recommended you use array rather than matrix. Matrices are always 2-D, whereas arrays can have any dimensionality. For this case, if your create 1-D arrays (check t.ndim), transposing does nothing since there is only one dimension.
I check the ndim and as you said, indeed for the np.array its just 1D while for the np.matrix is 2D; Thanks for pointing the problem

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.