I should be getting 16 individual lines, but the endpoint of the first line back tracks and meets the starting point of the next line. How do I fix this?
a = []
b = []
x = 0
for i in range(1,17):
for x in range(0,5):
y=x+i
a.append(x)
b.append(y)
fig= plt.figure()
axes=fig.add_subplot(111)
pylab.plot(a, b, '-b')
The problem is that you are trying to plot 16 lines but appending them all to a single list. The solution is to initialize empty lists each time and them plot them inside the for loop so that each list gets plotted as a single line.
You should define the figure only once outside the for loop in this case.
In the below answer, I am removing things which you don't need. For ex. x=0
and axes=fig.add_subplot(111)
. I am replacing this command by another variant.
Complete working answer:
import matplotib.pyplot as plt
fig, ax = plt.subplots(figsize=(8,6))
for i in range(1,17):
a = []
b = []
for x in range(0,5):
y=x+i
a.append(x)
b.append(y)
plt.plot(a, b, '-b')
plt.show()
Simpler version
You can simplify your whole code by making using of a numpy array as
import numpy as np
import matplotib.pyplot as plt
fig, ax = plt.subplots(figsize=(8,6))
a = np.arange(5)
for i in range(1,17):
plt.plot(a, a+i, '-b')
plt.show()
As you are appending all the answers in a single list, it assumes all lines are connected. You can try fixing sizes of a and b to 5 and then plot each of the 16 lines after each pass of the inner for loop.
for i in range(1,17):
for x in range(0,5):
y=x+i
a.append(x)
b.append(y)
pylab.plot(a, b, '-b')
a=[]
b=[]
fig= plt.figure()
axes=fig.add_subplot(111)
pylab.show()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.