Home > Blockchain >  How to plot values in a line plot with string xaxis?
How to plot values in a line plot with string xaxis?

Time:08-06

I have this df:

    Month MEAN
0   JAN    1.0
1   FEB    2.0
2   MAR    5.0
3   APR    3.0
4   MAY    4.0
5   JUN    2.0
6   JUL    1.0
7   AUG    1.0
8   SEP    0.0
9   OCT    0.0
10  NOV    2.0
11  DEC    3.0

I want to annotate the values of my plot in a lineplot graphic, so i tried this code:

fig = plt.figure('Graphic', figsize=(20,15), dpi=300)

ax1 = fig.add_axes([0.15, 0.20, 0.70, 0.60])
df.plot(kind='line', marker='o',style=['--'],linewidth=7,color='black', ms=15,ax=ax1)

for x,y in zip(df['Month'],df['MEAN']):

    label = "{:.2f}".format(y)

    plt.annotate(label, # this is the text
             (x,y), 
             textcoords="offset points", 
             xytext=(0,10), 
             ha='center')

But i get this error:

ConversionError: Failed to convert value(s) to axis units: 'JAN'

How can i solve this?

pd: Maybe i should change df['Month'] values to numerical but i need to plot the string values in the graphic.

Thanks in advance.

CodePudding user response:

This should work:

fig = plt.figure('Graphic', figsize=(20,15), dpi=300)

ax1 = fig.add_axes([0.15, 0.20, 0.70, 0.60])
df.plot(kind='line', marker='o',style=['--'],linewidth=7,color='black', ms=15,ax=ax1)

plt.xticks(range(0,len(df['Month'])), df['Month'])

plt.show()

Let me know if you have any questions.

CodePudding user response:

As you are aware, the x-axis value must be a number, not a string, so the graph can be created by using the data frame index and then setting the string ticks.

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure('Graphic', figsize=(10,7.5), dpi=72)

ax1 = fig.add_axes([0.15, 0.20, 0.70, 0.60])
df.plot(kind='line', marker='o', style=['--'], linewidth=7, color='black', ms=15, ax=ax1)

for x,y in zip(df.index, df['MEAN']):
    label = "{:.2f}".format(y)
    plt.annotate(label, # this is the text
             (x,y), 
             textcoords="offset points", 
             xytext=(0,10), 
             ha='center')
ax1.set_xticks(np.arange(0,12,1))
ax1.set_xticklabels(df['Month'].unique())

plt.show()

enter image description here

  • Related