Matplotlib Text Using a Condition

Matplotlib Text Using a Condition

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:

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 !

1

1 Answer

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:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Marcus Vance
Author

Marcus Vance

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.