枠線を変えたい

グラフの枠線の色を変更するには、spines属性を使用します。以下は修正されたコードです。

python
import matplotlib.pyplot as plt # スタイルを設定 plt.style.use('ggplot') # データを定義 x = [1, 2, 3, 4, 5] y = [2, 3, 5, 7, 11] # サブプロットを作成 fig, ax = plt.subplots() # 折れ線グラフをプロット ax.plot(x, y, marker='o', linestyle='-', color='b', label='Data', linewidth=2) # サブプロットにタイトルと軸ラベルを追加 ax.set_title('Sample Line Plot', fontfamily='serif') # フォントファミリーを指定 ax.set_xlabel('X-axis') ax.set_ylabel('Y-axis') # 凡例を表示 ax.legend() # グリッドを表示 ax.grid(True) # グラフの背景色を変更 ax.set_facecolor('lightgray') # グレーの背景色に変更 # 枠線の色を変更 for spine in ax.spines.values(): spine.set_edgecolor('black') # 黒色に変更 # グラフを表示 plt.show()

このコードでは、ax.spines.values()ですべての枠線を取得し、それぞれの枠線の色を黒色に変更しています。

未分類

Posted by ぼっち