[英]How differently do matplotlib.pyplot and seaborn treat numpy arrays?
Turns out that when trying to plot the same synthetically generated numpy arrays of 2D points (one with 12 data points and another with just 1) in both pyplot and seaborn, I have to change the array dimension of the single-point array so that the程序不會產生錯誤:
points = np.array([[1,2],[5,6],[4,1],[3,8],[7,5],[1,5],[0,8],[4,3],[2,1],[1,7],[3,8],[2,5]])
p = np.array([2.5,2])
import matplotlib.pyplot as plt
plt.style.use("ggplot")
plt.plot(points[:,0], points[:,1],"ro")
plt.plot(p[0],p[1], "bo")
plt.axis([0,7.5,0,8.5]);
使用上面的代碼,我可以得到正確的 pyplot。 但是,如果我嘗試使用 seaborn:
import seaborn as sns
sns.scatterplot(x = points[:,0], y = points[:,1])
sns.scatterplot(x = p[:,0], y = p[:,1])
我收到以下錯誤:
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-62-31fe2d015723> in <module>
1 import seaborn as sns
2 sns.scatterplot(x = points[:,0], y = points[:,1])
----> 3 sns.scatterplot(x = p[:,0], y = p[:,1])
IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed
盡管如此,如果我改變 p 數組的維度:
p = np.array([[2.5,2]])
它現在在 seaborn 中繪圖很好,但不再適用於使用 pyplot 繪圖。 它產生以下錯誤:
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-63-f26870ae2995> in <module>
5 plt.style.use("ggplot")
6 plt.plot(points[:,0], points[:,1],"ro")
----> 7 plt.plot(p[0],p[1], "bo")
8 plt.axis([0,7.5,0,8.5]);
IndexError: index 1 is out of bounds for axis 0 with size 1
有誰知道為什么會這樣?
您定義點p
的方式無關緊要。 您可以將p
定義為長度 = 1 的points
組:
p = np.array([[2.5,2]])
然后在pyplot中使用如下:
plt.plot(p[:,0],p[:,1], "bo")
在 seaborn 中:
sns.scatterplot(x = p[:,0], y = p[:,1])
或者,如果您真的想將點p
定義為一維數組,只需按如下方式傳遞它:
plt.plot(p[0], p[1], "bo")
sns.scatterplot(x = [p[0]], y = [p[1]])
像這樣傳遞它:
sns.scatterplot(x = [p[0]], y = [p[1]])
不要將值作為標量類型傳遞。 將其作為元素列表傳遞。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.