Matplotlib: Adding the DataFrame values to the plot

Viewed 139

I would like to print the DataFrame besides the plot. What would be a pythonic way to do that?

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({'Age':[21,22,23,24,25,26,27,28,29,30],'Count':[4,1,3,7,2,3,5,1,1,5]})
print(df)
   Age  Count
0   21      4
1   22      1
2   23      3
3   24      7
4   25      2
5   26      3
6   27      5
7   28      1
8   29      1
9   30      5

plt.rcParams['figure.figsize']=(10,6)
fig,ax = plt.subplots()
font_used={'fontname':'pristina', 'color':'Black'}
ax.set_ylabel('Count',fontsize=20,**font_used)
ax.set_xlabel('Age',fontsize=20,**font_used)
plt.plot(df['Age'],df['Count'])

I would like to have a Graph like this. How can I have the DataFrame's plotted values are printed alongside?: enter image description here

3 Answers

You can use ax.text to add the DataFrame to the plot. DataFrames have a .to_string method which makes formatting nice. Supply index=False to remove the row index.

plt.rcParams['figure.figsize']=(10, 6)
fig,ax = plt.subplots()
font_used={'fontname':'pristina', 'color':'Black'}
ax.set_ylabel('Count',fontsize=20,**font_used)
ax.set_xlabel('Age',fontsize=20,**font_used)

# Adjust to where you want. 
ax.text(x=28.5, y=4.5, s=df.to_string(index=False))

plt.plot(df['Age'],df['Count'])
plt.show()

enter image description here

Another option is to use the function plt.table():

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({'Age':[21,22,23,24,25,26,27,28,29,30],'Count':[4,1,3,7,2,3,5,1,1,5]})
plt.rcParams['figure.figsize']=(10,15)
fig,ax = plt.subplots()
plt.subplots_adjust(left=0.1, right=0.85, top=0.9, bottom=0.1)
font_used={'fontname':'pristina', 'color':'Black'}
ax.set_ylabel('Count',fontsize=20,**font_used)
ax.set_xlabel('Age',fontsize=20,**font_used)
plt.plot(df['Age'],df['Count'])
ax.table(cellText=df['Count'].map(str),
                  rowLabels=df['Age'].map(str),
                    colWidths=[0.2,0.25],
                  loc='right')
plt.show()

This approach will create a table with their respective lines. Just make sure to adjust the plot with subplots_adjust() afterwards.

enter image description here

Pandas has a to_html function you can use and place the html next to it. What are you placing the graph and Dataframe into?

df.to_html()
Related