如何在 Matplotlib Python 中繪製莖圖?
要在 Matplotlib 中繪製莖圖,我們可以使用 stem() 方法。它會從基線到 Y 座標建立垂直線,並在頂端放置一個標記。
步驟
- 設定圖形大小並調整子圖之間的邊距和周圍的邊距。
- 使用 numpy 建立 **x** 和 **y** 資料點。
- 使用 stem() 方法建立莖圖。
- 將標記面顏色設定為紅色。
- 要顯示圖形,請使用 show() 方法。
示例
import matplotlib.pyplot as plt import numpy as np plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True x = np.linspace(0.1, 2 * np.pi, 41) y = np.exp(np.sin(x)) markerline, stemlines, baseline = plt.stem(x, y, linefmt='grey', markerfmt='*', bottom=1.1) markerline.set_markerfacecolor('red') plt.show()
輸出
廣告