[英]How to create multiple series scatter plot with connected points using seaborn?
我有一組存儲在熊貓數據框中的數據。 我正在嘗試使用 seaborn 的 pointplot() 創建具有連接點的多系列散點圖。 每個系列都有不同的 (x,y) 值,它們以浮點數形式存儲在我的數據框中。 每行都有一個標簽,用於區分每個系列。 我使用的是 Python 2.7、seaborn 0.5.1 版和 matplotlib 1.4.3 版。
我設法找到的一切都告訴我,我可以通過以下方式實現這一目標:
import matplotlib.pyplot as plt
import seaborn as sns
# Suppose my dataframe is called 'df', with columns 'x', 'y', and 'label'.
sns.pointplot(x = 'x', y = 'y', hue = 'label', data = df)
然而,這會導致一些奇怪的行為:
我試圖通過將我的數據框分成幾部分來解決這個問題。 這並不理想,因為我可能有大約 10 個以上的系列要同時繪制,而且我不希望手動拆分數據:
df1 = df[df.test_type.values == "label 1"]
df2 = df[df.test_type.values == "label 2"]
ax = sns.pointplot(x = 'x',y='y', color = "blue", data = df1)
sns.pointplot(x = 'x', y = 'y', data = df2, color="red", ax = ax)
在這種情況下,所有點都連接在一起並且它們被適當地着色,但同樣,x 軸表現出非常奇怪的行為。 即使我的每個數據框中的 x 值不同,繪圖也會對齊它們,使它們看起來相同。
現在,我不確定如何干凈地發布我的輸出/繪圖,但是可以使用以下內容重新創建我的一些問題:
#import the necessary modules
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
#Here is some sample data. The 'x2' data is slightly offset from 'x1'
x1 = range(0,100,10)
x2 = range(1,100,10)
x = x1+x2
#The y-values I generate here mimic the general shape of my actual data
y1 = x1[::-1]
y2 = [i+25 for i in x1[::-1]]
y = y1+y2
#Two levels of labels that will be applied to the data
z1 = ["1"]*10
z2 = ["2"]*10
z = z1+z2
#A pandas data frame from the above data
df = pd.DataFrame({'x': x, 'y': y, 'z': z})
#Pointplot using the above data
sns.pointplot(x = 'x', y = 'y', data = df, hue = 'z')
運行此代碼會產生以下結果:
總結一下我的問題:
是否有更簡單/更好/更優雅的方法來使用存儲在 Pandas 數據框中的數據繪制具有連接點的多系列散點圖? Seaborn 的點圖看起來很理想,但它並沒有像我預期的那樣運行,我懷疑它的用途可能與我需要完成的目的不同。 我對可以實現這一點的其他解決方案持開放態度(最好使用 python)。
提前致謝。 如果我能弄清楚如何從我的代碼上傳輸出和繪圖,我會更新我的問題。
我是 stackoverflow 的 100% 新手。 我很想通過發布我的代碼生成的圖來澄清我的問題,但我無法弄清楚。 任何有關如何執行此操作的指示也將不勝感激,因此我可以更新問題。
編輯:事實證明,seaborn 的點圖使用 x 軸作為分類軸,這解釋了我上面提到的奇怪行為。 有沒有辦法手動將 x 軸行為從分類更改為數值? 這似乎是最簡單的方法,但我對 python 中的微調圖不是很熟悉。
我有一個類似的問題,我最終使用 Seaborn 的FacetGrid解決了它。 我使用 plt.scatter 作為點,使用 plt.plot 作為連接點的線。
g = sns.FacetGrid(df, hue="z", size=8)
g.map(plt.scatter, "x", "y")
g.map(plt.plot, "x", "y")
請注意,這是在 Seaborn 0.6.0 版和 0.5.1 版中完成的。
在@mwaskom 和這個問題的幫助下,我設法找到了我發布的問題的解決方案:
#Assuming df is a pandas data frame with columns 'x', 'y', and 'label'
for key,grp in df.groupby('label'):
plt.plot(grp.x,grp.y,'o-',label = key)
plt.legend(loc = 'best')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.