0

I have a dataframe with multiple columns (columns represent months) and each row is a group, e.g.

    OCT20  NOV20  DEC20  JAN21
A   20     24     19     18
B   45     29     33     46
C   19     11     13     11

(This is just dummy data to get a reproducible solution).

I am plotting a line plot of this dataframe, with the columns as x-ticks and each row in the index as a line in the plot, and the values for each month per row are the y values.

Below is the code I use for plotting, which works fine. However, I want to annotate each datapoint with its value from the dataframe, but with the code below I get all the datapoints in one place.

%matplotlib inline

labels = ['OCT20', 'NOV20', 'DEC20', 'JAN21', 'FEB21', 'MAR21']

ax = df.T.plot(grid = True, figsize=(20,15), marker='o')

for col in df.columns:
    for id, val in enumerate(df[col]):
        ax.text(id, val, str(val))

x = [0,1,2,3,4,5]
plt.xticks(x, labels, rotation=45)
    
plt.show()

And the output is this: enter image description here

But I want each datapoint to correspond to the correct marker in the plot.

Anyone know how to solve this?

0

1 Answer 1

1

You're so close! You've transposed the DataFrame, but then try to apply the text via the un-transposed DataFrame df:

plot_df = df.T  # Save the Transposition
ax = plot_df.plot(grid=True, figsize=(20, 15), marker='o')

for col in plot_df.columns:  # Use the Transposition
    for idx, val in enumerate(plot_df[col]):
        ax.text(idx, val, str(val))

x = [0, 1, 2, 3]
labels = ['OCT20', 'NOV20', 'DEC20', 'JAN21']
plt.xticks(x, labels, rotation=45)

plot


DataFrame used:

df = pd.DataFrame({
    'OCT20': {'A': 20, 'B': 45, 'C': 19},
    'NOV20': {'A': 24, 'B': 29, 'C': 11},
    'DEC20': {'A': 19, 'B': 33, 'C': 13},
    'JAN21': {'A': 18, 'B': 46, 'C': 11}
})
Sign up to request clarification or add additional context in comments.

1 Comment

Aaah indeed, it was such a small detail I overlooked. Thanks, it worked great!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.