Question

I am trying to graph two lists with matplotlib but I am getting an error regarding the dimension of x and y. One of the lists contains dates and the other numbers, you can see the content of the lists, I have printed them below.

I have tried checking the length of the lists with len() and they seem to be equal so I am a bit lost. I have checked several theads on this error without much luck.

Note: "query" contains my SQL query which I have not included for simplicity.

##### My code
t = 0
for row in query:
    data = query[t]
    date.append(data[0])
    close.append(data[1])
    t = t + 1

print "date = ", date
print "close = ", close
print "date length = ", len(date)
print "close length = ", len(close)

def plot2():
    plt.plot(date, close)
    plt.show()

plot2()
#

Output of my script:

date =  [datetime.datetime(2010, 1, 31, 22, 0), datetime.datetime(2010, 1, 31, 22, 1), datetime.datetime(2010, 1, 31, 22, 2), datetime.datetime(2010, 1, 31, 22, 3), datetime.datetime(2010, 1, 31, 22, 4), datetime.datetime(2010, 1, 31, 22, 5), datetime.datetime(2010, 1, 31, 22, 6), datetime.datetime(2010, 1, 31, 22, 7), datetime.datetime(2010, 1, 31, 22, 8), datetime.datetime(2010, 1, 31, 22, 9), datetime.datetime(2010, 1, 31, 22, 10)]

close =  [1.5945, 1.5946, 1.59465, 1.59505, 1.59525, 1.59425, 1.5938, 1.59425, 1.59425, 1.5939, 1.5939]

date length =  11

close length =  11

Traceback (most recent call last):
  File "script.py", line 234, in <module>
    plot2()
  File "script.py", line 231, in plot2
    plt.plot(date, close)
  File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 2467, in plot
    ret = ax.plot(*args, **kwargs)
  File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 3893, in plot
    for line in self._get_lines(*args, **kwargs):
  File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 322, in _grab_next_args
    for seg in self._plot_args(remaining, kwargs):
  File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 300, in _plot_args
    x, y = self._xy_from_xy(x, y)
  File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 240, in _xy_from_xy
    raise ValueError("x and y must have same first dimension")
ValueError: x and y must have same first dimension

Thanks in advance.

Was it helpful?

Solution

Works for me with your data.

Change your code and put the print statements inside the function.

def plot2():
    print "date = ", date
    print "close = ", close
    print "date length = ", len(date)
    print "close length = ", len(close)
    plt.plot(date, close)
    plt.show()

There must be something happing your code does not show.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top