Home > Software engineering >  Python display labels for the line series chart
Python display labels for the line series chart

Time:12-19

I'm trying to build a line chart with the labels, but I can't find how to achieve this. Basically, I want to have value for the point above the marker.

d = {'Year': ['2010', '2011', '2012', '2013', '2014', '2015', '2016', '2017', '2018', '2019'], 'Total': [1133.34262,1139.36454,1151.42072,1134.42854,1127.49346,1121.54558,1118.75674,1112.13016,1111.08126,1112.37696], 'Metric1':[444.4251,453.495,452.59418,454.63028,456.53064,456.17278,456.5183,455.35834,456.49362,456.4566], 'Metric2':[116.78576,116.13174,112.70122,112.49144,111.62764,108.74008,106.40782,105.61806,106.0623,104.74192], 'Metric3':[346.95144,346.24806,358.21786,350.06112,343.00264,338.49854,333.78466,329.88522,329.37928,331.36602], 'Metric4':[224.82246,223.58846,228.0432,217.09762,216.1351,217.83802,221.71278,221.10812,219.05968,219.38052]} 
df = pd.DataFrame(data=d)

df.plot( x="Year", 
         y=['Metric1','Metric2','Metric3','Metric4'],
         kind="line",
         figsize=(12,10),
         marker='o',
         linewidth=2
        )

plt.show()

enter image description here

CodePudding user response:

To add labels above the markers in your line chart, you make a good use of the Text function from Matplotlib's pyplot module. You can do this by iterating through the data points in your line chart and adding a Text label for each point.

Example:

import matplotlib.pyplot as plt


df.plot( x="Year", 
         y=['Metric1','Metric2','Metric3','Metric4'],
         kind="line",
         figsize=(12,10),
         marker='o',
         linewidth=2
        )

# Get the current Axes object
ax = plt.gca()

# Iterate through the data points and add a text label for each point
for line in ax.get_lines():
    x, y = line.get_data()
    for i in range(len(x)):
        ax.text(x[i], y[i], f'{y[i]:.2f}', ha='center', va='bottom')

plt.show()

Output: enter image description here

CodePudding user response:

You may simply use matplotlib's text function to achieve this.

First convert df['Year'] from string to float:

df['Year'] = df['Year'].astype(float)

Then iterate over the rows of your pandas dataframe and plot the label corresponding to Metric1 above each point of coordinates (Year, Metric1). You may use a padding parameter to improve the visual aspect and ensure that the label does not overlap with the points:

padding = 2
for index, row in df.iterrows():
    plt.text(np.float(row['Year']), row['Metric1'] padding, row['Metric1'])

This snippet yields the following image:

enter image description here

You may repeat the same steps for the other Metrics.

  • Related