Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 !

>Solution :

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) 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading