python - 我将如何绘制点并在 python 中画一条线?
问题描述
所以我应该绘制图表。制作一个函数 plot_line(p1,p2),它将两个点作为输入参数并绘制它们之间的线。两个输入参数应该是指定 x 和 y 坐标的列表或元组,即 p1 =(x1,y1)
我试过这个,但我的图表在绘图表中只是空的。什么都没有出现
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()
解决方案
Complementing Prateek Tripathi and according to what I understood. There are two things you need to fix in your code.
Plotting
For more information on how to 'nicely' plot check matplotlib documentation
Your implementation
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)
At the end
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