add name of people to the scatterplot

Question:

I have a dataset of 6 people, which is called df

People Height weight
Neil 186 90
Olaf 187 60
Jake 188 75
Mitt 189 77
Gaby 181 62
Sam 180 65

Now I would like to to do a scatterplot which shows the name of the people in above left of the point in the scatterplot. but i don’t get the name of the people.

I did these

_, ax=plt.subplots(figsize=(5,5))
s = sns.scatterplot(x=df['Height'], y=df['weight'], ax=ax) 
g.set(xlabel='height', ylabel='weight')
plt.title("relationship between height and weight");
Asked By: Jay

||

Answers:

You can do this using plotly (question does not state a certain library):

import plotly.express as px
import pandas as pd

df = pd.DataFrame.from_dict(
    {
        "People": {0: "Neil", 1: "Olaf", 2: "Jake", 3: "Mitt", 4: "Gaby", 5: "Sam"},
        "Height": {0: 186, 1: 187, 2: 188, 3: 189, 4: 181, 5: 180},
        "weight": {0: 90, 1: 60, 2: 75, 3: 77, 4: 62, 5: 65},
    }
)

px.scatter(
    df,
    x="Height",
    y="weight",
    text="People",
    height=500,
    width=500,
    title="relationship between height and weight",
).update_traces(textposition="top left", textfont_size=18)

enter image description here

Answered By: Saaru Lindestøkke

Here is how you would manually add them using seaborn


import seaborn as sns

# Create a dataframe with weight, height, and people data
data = {
    'weight': [68, 70, 72, 65, 58, 59, 64, 68, 69, 71],
    'height': [175, 179, 180, 166, 159, 162, 168, 172, 173, 177],
    'people': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
}
df = pd.DataFrame(data)

# Create a scatter plot with labels
ax = sns.scatterplot(x='weight', y='height', data=df)

# Add labels to each point
for line in range(0, df.shape[0]):
     ax.text(df.weight[line]+0.1, df.height[line], df.people[line], horizontalalignment='left', size='medium', color='black', weight='semibold')


enter image description here

Answered By: Conic
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.