user1234115
user1234115

Reputation: 13

Python simple linear plotting

So I'm trying to plot 2 different arrays of the same dimensions using python's matplotlib. This is the code I currently have:

from numpy import *
from pylab import *
import matplotlib.pyplot as plt
p, pdot, s400, dist=loadtxt("cc45list.txt", usecols=(1,2,3,4), unpack=True)
for i in arange(0,45,1):
 k = (s400*(dist**2))/((p**1)*(pdot**0.5))
 kbar=sum(k)
 var=abs(k-kbar)
 x=((p**1)*(pdot**0.5))
 y=s400*(dist**2)

kbararray=ones((1,45))*kbar

I'm trying to plot a simple line with the xaxis being x and the yaxis being kbararray (which is just an array of the same value calculated in the loop). I tried using this bit of matplotlib which has worked in the past for my other plots:

plot(x,kbararray)

But I keep end up recieveing this error message:

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

From what I've researched this error usually comes up if you try to plot 2 arrays of different dimensions but I'm sure mine are of the same dimension, right? So why would I be getting this error? Sorry if this is a basic question/answered elsewhere but I couldn't find anything. Thanks.

Upvotes: 1

Views: 1214

Answers (2)

Leo Uieda
Leo Uieda

Reputation: 203

The problem is in this line:

kbararray=ones((1,45))*kbar

You see, you're declaring kbararray as having shape (1, 45), which is not the same shape as the x array, which has shape (,45). If you want kbararray to have the same shape as x, you can use:

kbararray=ones_like(x)*kbar

Upvotes: 0

Brendan Wood
Brendan Wood

Reputation: 6450

You can verify that they are the same shape by printing the shape of x and kbararray at runtime. Right before you call plot, add these lines:

print 'Shape of x:', x.shape
print 'Shape of kbararray:', kbararray.shape

If the shapes are different, you have a problem and should check that you are actually plotting what you think you're plotting.

Upvotes: 1

Related Questions