Reputation: 63
So Im supposed to plot graphs. Make a function plot_line(p1,p2) that takes two points as input arguments and plots the line between them. The two input arguments should be lists or tuples specifying x- and y-coordinates, i.e., p1 =(x1,y1)
I tried with this but my graph is just empty in the plot table. Nothing comes up
import matplotlib.pyplot as plt
print('this code will plot two points in a graph and make a line')
x1 = (float(input('enter first x value: ')))
y1 = (float(input('enter first y value: ')))
x2 = (float(input('enter second x value: ')))
y2 = (float(input('enter second y value: ')))
def plotline(p1,p2):
p1=[x1,y1]
p2=[x2,y2]
return p1,p2
x=plotline(x1,x2)
y=plotline(x1,x2)
plt.plot(x,y, label='x,y')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.axis([-10,10,-10,10])
plt.title('two lines')
plt.show()
Upvotes: 1
Views: 3618
Reputation: 136
Complementing Prateek Tripathi and according to what I understood. There are two things you need to fix in your code.
For more information on how to 'nicely' plot check matplotlib documentation
Your function plotline
it's acting weird and and I think it doesn't do what it should. Try with this one
def plotLine(p1, p2):
x = (p1[0], p2[0]) # Extracting x's values of points
y = (p1[1], p2[1]) # Extracting y's values of points
plt.plot(x,y, '-o',label='x,y') # Plotting points
where p1
and p2
must be tuples of the coordinates corresponding to the points of your line. The tuples can be created manually by (x1, y1)
and (x2, y2)
; or with a function similar the next one
def coordinates2tuple(x, y):
return (x, y)
your code could looks like
import matplotlib.pyplot as plt
def coordinates2tuple(x, y):
return (x, y)
def plotLine(p1, p2):
x = (p1[0], p2[0]) # Extracting x's values of points
y = (p1[1], p2[1]) # Extracting y's values of points
plt.plot(x,y, '-o',label='x,y') # Plotting points
print('this code will plot two points in a graph and make a line')
x1 = (float(input('enter first x value: ')))
y1 = (float(input('enter first y value: ')))
x2 = (float(input('enter second x value: ')))
y2 = (float(input('enter second y value: ')))
p1 = coordinates2tuple(x1, y1)
p2 = coordinates2tuple(x2, y2)
plotLine(p1, p2)
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid()
plt.axis([-10,10,-10,10])
plt.title('two lines')
plt.show()
That with the next execution
$ python3 trs.py
this code will plot two points in a graph and make a line
enter first x value: 0
enter first y value: 0
enter second x value: 1
enter second y value: 1
Upvotes: 1
Reputation: 11
plt.plot() takes three input to work
If you just write plt.plot(3,4), it only pins the location but doesn't point it.
You need to write plt.plot(3,4,'o'). this way you will pin and point the location with a 'o' structure
Upvotes: 1