Home > Net >  Show text for particular points of line chart in matplotlib
Show text for particular points of line chart in matplotlib

Time:11-09

I need to show text for points that have only the maximum and minimum values so I can avoid text overlapping as shown in the image.

enter image description here

Here is the code

x = df['Measurement Date']
y = df['SYS']
  
plt.plot(x, y)

plt.rcParams['figure.figsize'] = (15, 10)

for x, y in zip(df['Measurement Date'], df['SYS']):
    plt.text(x = x, y = y, s = '{:.0f}'.format(y))

plt.show()

CodePudding user response:

This can be achieved by looping through the data frame with the minimum and maximum values extracted from the data frame.

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv('./data/bp_log.csv')
min_max = df[(df['SYS'] == df['SYS'].min()) | (df['SYS'] == df['SYS'].max())] 
x = df['Measurement Date']
y = df['SYS']
  
plt.plot(x, y)

plt.rcParams['figure.figsize'] = (15, 10)

#for x, y in zip(df['Measurement Date'], df['SYS']):
for x, y in zip(min_max['Measurement Date'], min_max['SYS']):
    plt.text(x = x, y = y, s = '{:.0f}'.format(y))

plt.show()
  • Related