how to append to y value in matplotlib

793 views Asked by At

I'm having trouble plotting a graph which takes data read from a file and saves the graph onto a pdf file. Now the pdf file is created but does not open because none of the plots is being added to it (I have about 18 plots) or you can say none is being plotted in the first place. and I'm also receiving this type of error:

raise ValueError("x and y must have same first dimension")
ValueError: x and y must have same first dimension

This is part of the code:

# plot 16: plotting absolute mag vs perihelion distance
text = 'Number of data points: %s' %NumCounts

x = np.array([0,1,2,3,4])
y = np.array([])
for point in range(len(x)):
    y.append(11.4 - 1.96 * point)

plt.figure()
plt.clf()

#ax = fig.add_subplot(111)

plt.plot(perihelion,absolute_mag_average, 'b.')
plt.plot(x,y,'r')
plt.text(0.5, 4, 'H = 11.4 - 1.96q', fontsize = 12)

plt.text(6, 23, text, fontsize = 12)
plt.title("Absolute mag vs Perihelion distance")
plt.xlabel('Perihelion (AU)', fontsize = 13)
plt.ylabel('Absolute mag', fontsize = 13)
ax = fig.add_subplot(111)
createPDF.savefig()
2

There are 2 answers

0
jcoppens On
plt.plot(perihelion,absolute_mag_average, 'b.')
plt.plot(x,y,'r')

The second plot (where x and y are taken from the code you showed) seems correct, but did you check in the first one if the size of perihelion and absolute_mag_average arrays are the same?

Print out the len of both. I suspect they're different.

0
James On

You have an indentation error when defining y. It should read

for point in range(len(x)):
    y.append(11.4 - 1.96 * point)

The other parts look OK. You can explicitly create and reference your figure using:

fig, ax = plt.subplots(1)

if you want.