Hey Guys,

I'm trying to do a basic line graph here, but I can't seem to figure out how to adjust my x axis.

from pylab import *

plot ( range(0,10),[9,4,5,2,3,5,7,12,2,3],'.-',label='sample1' )
plot ( range(0,10),[12,5,33,2,4,5,3,3,22,10],'o-',label='sample2' )
xlabel('x axis')
ylabel('y axis')
title('my sample graphs')
legend(('sample1','sample2'))
savefig("sampleg.png",dpi=(640/8))

show()

And here is the error I get when I try adjusting my range.

File "C:\Python26\lib\site-packages\matplotlib\axes.py", line 228, in _xy_from_xy
    raise ValueError("x and y must have same first dimension")
ValueError: x and y must have same first dimension

I want my range to be a list of strings: ["12/1/2007","12/1/2008", "12/1/2009","12/1/2010"

Any suggestions?

Dani AI

Generated

The traceback means matplotlib received x and y arrays with different lengths. In your follow-up you switched the x range to 11 values while your y list still had 10 — that causes the ValueError. A simple, robust pattern is to plot against numeric positions that are guaranteed to match your data length, then attach the date strings as tick labels.

import matplotlib.pyplot as plt

labels = ['Dec-07', 'Dec-08', 'Dec-09', 'Dec-10']
y = [9, 4, 5, 2]

x = list(range(len(y)))          # always matches y
plt.plot(x, y, 'o-')
plt.xticks(x, labels, rotation=30)
plt.tight_layout()
plt.show()

If you want a real time axis (so matplotlib can place ticks by year/month and handle spacing), convert the strings to datetime objects and use matplotlib.dates:

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime

date_strs = ['12/01/2007','12/01/2008','12/01/2009','12/01/2010']
dates = [datetime.strptime(s, '%m/%d/%Y') for s in date_strs]
y = [9, 4, 5, 2]

plt.plot(dates, y, marker='o')
ax = plt.gca()
ax.xaxis.set_major_locator(mdates.YearLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))
plt.gcf().autofmt_xdate()
plt.show()

Notes tied to earlier posts: ’s hint to show the full traceback was useful — it reveals the length mismatch. ’s string-building example demonstrates a common gotcha: concatenating pieces can produce unexpected years (e.g. '200' + '10' -> '20010'); prefer numeric year math or an explicit year range (for example, use range(2007,2011) or format the year). Extra tips: before plotting, assert len(x) == len(y); use plt.tight_layout() or autofmt_xdate() to avoid clipped tick labels; use pandas.to_datetime if you already work with DataFrame timestamps.

Recommended Answers

All 4 Replies

>>> ["12/1/200"+str(x) for x in range(7,11)]
['12/1/2007', '12/1/2008', '12/1/2009', '12/1/20010']
>>>

You will have to include the complete error message, which prints the line where the error was found. We are volunteers so no one will take the time to try and guess which line is causing the error.

A complete error message looks like this:

 ./test_1.py
  File "./test_1.py", line 20
    if start > -1
                ^
SyntaxError: invalid syntax
Traceback (most recent call last):
  File "C:\PortablePython_1.1_py2.6.1\App\April_2010\graphing lines.py", line 3, in <module>
    plot ( range(0,11),[9,4,5,2,3,5,7,12,2,3],'.-',label='sample1' )
  File "C:\PortablePython_1.1_py2.6.1\App\Lib\site-packages\matplotlib\pyplot.py", line 2141, in plot
    ret = ax.plot(*args, **kwargs)
  File "C:\PortablePython_1.1_py2.6.1\App\Lib\site-packages\matplotlib\axes.py", line 3432, in plot
    for line in self._get_lines(*args, **kwargs):
  File "C:\PortablePython_1.1_py2.6.1\App\Lib\site-packages\matplotlib\axes.py", line 311, in _grab_next_args
    for seg in self._plot_args(remaining, kwargs):
  File "C:\PortablePython_1.1_py2.6.1\App\Lib\site-packages\matplotlib\axes.py", line 288, in _plot_args
    x, y = self._xy_from_xy(x, y)
  File "C:\PortablePython_1.1_py2.6.1\App\Lib\site-packages\matplotlib\axes.py", line 228, in _xy_from_xy
    raise ValueError("x and y must have same first dimension")
ValueError: x and y must have same first dimension

I tried to install matplotlib/pylab to run your code but there are problems with the png dependency and I can't spend any more time on it now. Anyway, this line seems to be the problem

plot ( range(0,11),[9,4,5,2,3,5,7,12,2,3],'.-',label='sample1' )
##
##   try using this and see if there is any difference
##
x_list = arange(range(0,11))
y_list = arange([9,4,5,2,3,5,7,12,2,3])
plot( x_list, y_list, 'b')
show()
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.