如何在 Python 中繪製圖形?


可以使用 Matplotlib 庫在 Python 中繪製圖形。 Matplotlib 庫 主要用於圖形繪製。

在使用 Matplotlib 繪製圖形之前,您需要安裝 matplotlib。Matplotlib 用於繪製簡單的線條、條形圖、直方圖和餅圖。Matplotlib 庫中提供了繪製各種圖形的內建函式。

在圖形中繪製一條線

我們將使用 matplotlib 在圖形中繪製一條簡單的線。繪製線條涉及以下步驟。

  • 匯入 matplotlib

  • 指定線的 x 座標和 y 座標

  • 使用特定函式(使用 .plot() 函式)繪製指定的點

  • 使用 .xlabel() .ylabel() 函式命名 x 軸和 y 軸

  • 使用  .title() 函式為圖形新增標題(可選)

  • 使用  .show() 函式顯示圖形

這些是在使用 matplotlib 繪製線條時涉及的簡單步驟。

示例

import matplotlib.pyplot as plt

x=[1,3,5,7]
y=[2,4,6,1]
plt.plot(x,y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title("A simple line graph")
plt.show()

以上程式碼繪製了點 (1,2)、(3,4)、(5,6)、(7,1) 並用線連線這些點,顯示為圖形。

輸出

繪製條形圖

條形圖是以不同高度的矩形在 x 軸上的特定位置表示資料的方式。

繪製條形圖涉及以下步驟:

  • 匯入 matplotlib

  • 指定矩形左下角所在的 x 座標。

  • 指定條形或矩形的高度。

  • 指定條形的標籤

  • 使用 .bar() 函式繪製條形圖

  • 為 x 軸和 y 軸新增標籤

  • 為圖形新增標題

  • 使用 .show() 函式顯示圖形。

示例

import matplotlib.pyplot as plt

left_coordinates=[1,2,3,4,5]
heights=[10,20,30,15,40]
bar_labels=['One','Two','Three','Four','Five']
plt.bar(left_coordinates,heights,tick_label=bar_labels,width=0.6,color=['re
d','black'])
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title("A simple bar graph")
plt.show()

plt.bar() 中的 width 引數指定每個條形的寬度。顏色列表指定條形的顏色。

輸出

更新於: 2023-08-23

59K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告