4

I have this dataframe:

    key variable    value
0   0.25    -0.2    606623.455859
1   0.27    -0.2    621462.029200
2   0.30    -0.2    640299.078053
3   0.33    -0.2    653686.910706
4   0.35    -0.2    659278.593742
5   0.37    -0.2    665684.466383
6   0.40    -0.2    671975.695814
7   0.25    0   530091.733402
8   0.27    0   542501.852937
9   0.30    0   557799.179433
10  0.33    0   571140.149887
11  0.35    0   575117.783803
12  0.37    0   582709.048163
13  0.40    0   588168.965913
14  0.25    0.2 466275.721535
15  0.27    0.2 478678.452615
16  0.30    0.2 492749.041489
17  0.33    0.2 500792.917910
18  0.35    0.2 503620.638204
19  0.37    0.2 507884.996510
20  0.40    0.2 512504.976664
21  0.25    0.5 351579.595889
22  0.27    0.5 359555.855803
23  0.30    0.5 368924.362358
24  0.33    0.5 375069.238800
25  0.35    0.5 377847.414729
26  0.37    0.5 381146.573247
27  0.40    0.5 383836.933547

And I am trying to make a contour plot using this dataframe with the following code:

x = df['key'].values
y = df['variable'].values
z = df['value'].values
plt.tricontourf(x, y, z, colors='k')

I keep getting this error:

ValueError: x and y must be 1D arrays of the same length

But whenever I check the len, .size, .shape, and .ndim of x and y, they are 1D arrays of the same length. Does anyone know why I would get this error?

x.shape returns (28L,) and y.shape returns (28L,) as well

Rushwin Jamdas
  • 344
  • 1
  • 5
  • 18

2 Answers2

6

Okay I found a way to make it work. Really not sure why it didn't work the original way because I was feeding tricontourf 1D arrays, but basically I wrarpped my data in a list() function just to double make sure it was 1D arrays. This made it work. Here's the code:

x = df_2020_pivot['key'].values
y = df_2020_pivot['variable'].values
z = df_2020_pivot['value'].values
plt.tricontourf(list(x), list(y), list(z))

plt.show()

And this is what it produced

Rushwin Jamdas
  • 344
  • 1
  • 5
  • 18
1

I had the same issue crop up. I was passing in two numpy arrays of the same length, and got the 'must be 1D arrays of same length' error. Looking at type(array), the arrays I was passing in were numpy.ndarrays. I used array.tolist() to turn them into simple (1D) lists, and this removed the error for me. Wrapping in the list() function as mentioned above also works.

x = df['key'].values.tolist()
y = df['variable'].values.tolist()
z = df['value'].values
plt.tricontourf(x, y, z, colors='k')
JCollinski
  • 54
  • 1
  • 6