我有以下資料框:
data = {'Var1':[3, 8, 4, 2, 13],
'Var2':[5, 7, 9, 10, 15],
'Name':['obs1', 'obs2', 'obs3', 'obs4', 'obs5']}
df1 = pd.DataFrame(data)
我根據變數“名稱”添加標簽:
import seaborn as sns
sns.scatterplot(data=df1,x='Var1',y='Var2')
for i in range(df1.shape[0]):
plt.text(x=df1.Var1[i] 0.3, y=df1.Var2[i] 0.3,s=df1.Name[i],
fontdict=dict(color="black",size=10),
bbox=dict(facecolor="white",alpha=0.5))
結果如下:

現在我想在兩種情況下顯示標簽:如果觀察值高于 14 和低于 8,那么我會顯示標簽。
你有解決方案嗎 ?謝謝 !
uj5u.com熱心網友回復:
您可以在回圈中使用一個簡單的條件。這里我跳過回圈 if 8<Val2<14 使用continue關鍵字:
import seaborn as sns
sns.scatterplot(data=df1,x='Var1',y='Var2')
for i in range(df1.shape[0]):
if 8<df1.Var2[i]<14:
continue
plt.text(x=df1.Var1[i] 0.3, y=df1.Var2[i] 0.3,s=df1.Name[i],
fontdict=dict(color="black",size=10),
bbox=dict(facecolor="white",alpha=0.5)
)
輸出:

替代代碼格式
我借此機會向您展示一種更簡潔的代碼方式(在我看來):
import seaborn as sns
sns.scatterplot(data=df1,x='Var1',y='Var2')
options = dict(fontdict=dict(color="black",size=10),
bbox=dict(facecolor="white",alpha=0.5))
for i, (x,y,name) in df1.iterrows():
if y<8 or y>14:
plt.text(x=x 0.3, y=y 0.3, s=name, **options)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/371124.html
標籤:Python 循环 matplotlib 海生
下一篇:創建一個流以生成三個的倍數
