Home > database >  Matplotlib weird behavior with 2D arrays plot
Matplotlib weird behavior with 2D arrays plot

Time:11-20

As per the matplotlib documentation, x and/or y may be 2D arrays, and in this case the columns are treated as different datasets. When I follow the enter image description here

if I plot them separately, it comes out fine:

fig, ax = plt.subplots()
ax.plot(x,chi2_2,'b')
ax.plot(x,chi2_5,'r')

enter image description here

I can't figure out what is the difference between the example and my case other then using 2D arrays with Float64 instead of Int64. Any help is appreciated.

CodePudding user response:

It looks like reshape isn't doing what you expect it to do. I think the function that you are looking for is transpose rather than reshape.

from scipy.stats import chi2

x = np.linspace(0,5,1000)
chi2_2, chi2_5 = chi2.pdf(x,2), chi2.pdf(x,5)

y = np.array((chi2_2,chi2_5)).T
y2 = np.array((chi2_2,chi2_5)).reshape(1000,2)
print(np.array_equal(y,y2))
fig, ax = plt.subplots()
ax.plot(x,y)
plt.show()

Using transpose returns the plot that you want and np.array_equal(y,y2) being False confirms that the 2 arrays are not the same.

Below is the output:

enter image description here

  • Related