[英]Python Plotly: Adding a horizontal line to a scatter plot that has multiple subplots
[英]Adding line to scatter diagram in matplotlib with subplots
我有四個子圖(排列為 2x2),我想為這些散點圖添加一條最適合的線,但是數據太多,無法手動計算和輸入。
我查看了類似的問題,因為它們被格式化為一個 plot 我無法弄清楚如何為我的代碼安排這個。
到目前為止,我已經...
fig, ax = plt.subplots(2,2, figsize=(20,18))
ax[0,0].scatter(x,y1, color='tab:blue')
ax[0,0].set_xlabel('Title One',fontsize =15)
ax[0,0].set_ylabel('Title Two',fontsize =15)
等等......完成:
plt.show()
我的地塊具有相同的 x 軸,四個不同的 y 軸標記為 y1,y2,y3,y4
散點圖 plot 的最佳擬合線代碼已在此處得到解答。 對於其他子圖,您可以將索引從ax[0, 0]
更改為其他索引,例如ax[0, 1]
。 因為您正在創建一個 2x2 子圖,所以索引是ax[0,0]
、 ax[0,1]
、 ax[1,0]
和ax[1,1]
。
因此,為多個子圖實施,將是:
import numpy as np
import matplotlib.pyplot as plt
x = np.random.normal(0, 1, 15)
y1 = np.random.normal(0, 1, 15)
y2 = np.random.normal(0, 1, 15)
y3 = np.random.normal(0, 1, 15)
y4 = np.random.normal(0, 1, 15)
fig, ax = plt.subplots(2,2, figsize=(20,18))
ax[0,0].scatter(x, y1, color='tab:blue')
ax[0,0].plot(np.unique(x), np.poly1d(np.polyfit(x, y1, 1))(np.unique(x)))
ax[0,0].set_xlabel('Title One', fontsize=15)
ax[0,0].set_ylabel('Title Two', fontsize=15)
ax[0,1].scatter(x, y2, color='tab:blue')
ax[0,1].plot(np.unique(x), np.poly1d(np.polyfit(x, y2, 1))(np.unique(x)))
ax[0,1].set_xlabel('Title One', fontsize=15)
ax[0,1].set_ylabel('Title Two', fontsize=15)
ax[1,0].scatter(x, y3, color='tab:blue')
ax[1,0].plot(np.unique(x), np.poly1d(np.polyfit(x, y3, 1))(np.unique(x)))
ax[1,0].set_xlabel('Title One', fontsize=15)
ax[1,0].set_ylabel('Title Two', fontsize=15)
ax[1,1].scatter(x, y4, color='tab:blue')
ax[1,1].plot(np.unique(x), np.poly1d(np.polyfit(x, y4, 1))(np.unique(x)))
ax[1,1].set_xlabel('Title One', fontsize=15)
ax[1,1].set_ylabel('Title Two', fontsize=15)
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.