簡體   English   中英

我將如何在 python 中繪制點並畫一條線?

[英]How would I plot points and make a line in 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()
    

plt.plot()需要三個輸入才能工作

如果你只是寫plt.plot(3,4) ,它只會固定位置而不是指向它。

你需要寫plt.plot(3,4,'o')。 這樣,您將使用“o”結構固定並指向該位置

根據我的理解,補充Prateek Tripathi 您需要在代碼中修復兩件事。

繪圖

有關如何“很好地”繪制檢查matplotlib 文檔的更多信息

您的實施

你的功能plotline得很奇怪,而且我認為它沒有做它應該做的。 試試這個

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

其中p1p2必須是與您的線的點相對應的坐標的元組。 元組可以通過(x1, y1)(x2, y2)手動創建; 或具有類似於下一個的功能

def coordinates2tuple(x, y):
    return (x, y)

在末尾

你的代碼可能看起來像

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()

下一次執行

$ 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

顯示在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM