Rohit
Rohit

Reputation: 465

Add text annotation to plot from a pandas dataframe

My Code:

import matplotlib.pyplot as plt
import pandas as pd
import os, glob

path = r'C:/Users/New folder'
all_files = glob.glob(os.path.join(path, "*.txt"))
df = pd.DataFrame()
for file_ in all_files:
    file_df = pd.read_csv(file_,sep=',', parse_dates=[0], infer_datetime_format=True,header=None, usecols=[0,1,2,3,4,5,6], names=['Date','Time','open', 'high', 'low', 'close','volume','tradingsymbol'])

df = df[['Date','Time','close','volume','tradingsymbol']]
df["Time"] = pd.to_datetime(df['Time'])
df.set_index('Time', inplace=True)
print(df)

fig, axes = plt.subplots(nrows=2, ncols=1)
################### Volume ###########################
df.groupby('tradingsymbol')['volume'].plot(legend=True, rot=0, grid=True, ax=axes[0])
################### PRICE ###########################
df.groupby('tradingsymbol')['close'].plot(legend=True, rot=0, grid=True, ax=axes[1])

plt.show()

My Current Output is like: Output

I need add text annotation to matplotlib plot. My desired output similar to below imageDesired:

Upvotes: 1

Views: 6413

Answers (1)

jwalton
jwalton

Reputation: 5686

It's hard to answer this question without access to your dataset, or a simpler example. However, I'll try my best.

Let's begin by setting up a dataframe which may or may resemble your data:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.randint(low=0, high=10, size=(5, 3)),
                    columns=['a', 'b', 'c'])

With the dataset we'll now proceed to plot it with

fig, ax = plt.subplots(1, 1)
df.plot(legend=True, ax=ax)

Finally, we'll loop over the columns and annotate each datapoint as

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

This gave me the plot following plot, which resembles your desired figure. enter image description here

Upvotes: 6

Related Questions