Home > Software design >  Matplotlib text using a condition
Matplotlib text using a condition

Time:12-01

I have the following dataframe:

data = {'Var1':[3,  8,  4,  2, 13],
        'Var2':[5,  7,  9,  10, 15],
        'Name':['obs1', 'obs2', 'obs3', 'obs4', 'obs5']}  
df1 = pd.DataFrame(data)

And I add labels according to the variable "Name":

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))

Here is the result:

1

Now i would like to show the labels under two conditions : if the observations are above 14 and below 8, then I show the labels.

Do you have a solution ? Thank you !

CodePudding user response:

You can just use a simple condition in your loop. Here I skip the loop if 8<Val2<14 using the continue keyword:

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)
            )

output:

enter image description here

alternative code formatting

I take the opportunity to show you a cleaner way for your code (In my opinion):

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) 
  • Related