Display the values on the line plot in SNS line chart

Question:

I am trying to annotate the values on the SNS line plot but i am not able to annotate it. Below code for my line plot,

import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib.dates as mdates
fig, ax = plt.subplots(figsize = (12,5))
ax.set_title("Daily Closing Price")
ax.set_ylabel("Values")
ax.set_xlabel("Date")
#ax.tick_params(axis='x', rotation=50)

#ax.set_xticks(Categories)

p1 = sns.lineplot(ax=ax, x='Date', y='Prev Close', data=result, hue='Symbol', markers=True, dashes=False, marker="o")

plt.xticks(rotation=45,horizontalalignment='right',fontweight='light')
locator = mdates.DayLocator(interval=1)
p1.xaxis.set_major_locator(locator)

Below image is expected output with annotated values (Manually i annotated the values but I want it in my code):

enter image description here

Asked By: user286076

||

Answers:

Here is an example to annotate values on line graph:

import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt

# Data Load
df = pd.DataFrame(data={'Date': ['2022-11-28', '2022-11-29', '2022-11-30', '2022-12-01', '2022-12-02'],
                      'closing_price_1': [ 15, 26, 30, 39, 50],
                      'closing_price_2': [ 12, 18, 23, 33, 41]})

# Create the line plot
ax = sns.lineplot(x="Date", y="closing_price_1", data=df)
ax = sns.lineplot(x="Date", y="closing_price_2", data=df)
plt.ylabel('Values')
plt.title('Daily Closing Price')

# Add annotations
for line in range(0,df.shape[0]):
     ax.text(df.Date[line], df.closing_price_1[line], df.closing_price_1[line], horizontalalignment='left', size='medium', color='black', weight='semibold')
     ax.text(df.Date[line], df.closing_price_2[line], df.closing_price_2[line], horizontalalignment='left', size='medium', color='black', weight='semibold')

Should output as follows:
enter image description here

Answered By: Sadman Sakib
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.