Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add text annotation to matplotlib plot from a pandas dataframe

How to add text annotations and mark plotted points and the numeric values to a matplotlib plot of a pandas dataframe? The columns of the dataframe are not a fixed size, they vary for different files.

dataframe = pd.read_csv('file1.csv')

plt.figure(figsize=(50,25))
dataframe.plot()
plt.xticks(rotation=45, fontsize=8)
plt.yticks(fontsize=8)
like image 824
ArchieTiger Avatar asked Jun 06 '16 15:06

ArchieTiger


People also ask

How do you annotate in pandas plot?

Create a figure and a set of subplots using subplots() method. Plot a series of data frame using plot() method, kind='scatter', ax=ax, c='red' and marker='x'. To annotate the scatter point with the index value, iterate the data frame. To display the figure, use show() method.

How do I annotate in matplotlib?

Annotating with Arrow. The annotate() function in the pyplot module (or annotate method of the Axes class) is used to draw an arrow connecting two points on the plot. This annotates a point at xy in the given coordinate ( xycoords ) with the text at xytext given in textcoords .

How do I add a label to a plot in pandas?

You can set the labels on that object. Or, more succinctly: ax. set(xlabel="x label", ylabel="y label") . Alternatively, the index x-axis label is automatically set to the Index name, if it has one.


1 Answers

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

df = pd.DataFrame({'x':range(0, 100, 20),
                   'y':np.random.randint(0,100,5)})

rows, cols = df.shape
fig, ax = plt.subplots(figsize=(50/10,25/10))
df.plot(ax=ax)

for col in range(cols):
    for i in range(rows):
        ax.annotate('{}'.format(df.iloc[i, col]), xy=(i, df.iloc[i, col])) 
plt.xticks(rotation=45, fontsize=8)
plt.yticks(fontsize=8)

plt.show()

enter image description here

like image 194
MaThMaX Avatar answered Oct 14 '22 06:10

MaThMaX