How to plot image and text using Python matplotlib
Do you know how to plot image and text on matplotlib? This makes graph looks better. Let’s try.
Today, I’m going to use these data as below:
import pandas as pd
records = pd.read_csv('data.csv')
records
These are wins and ages of Major League Baseball teams in National League west division.
If you’d like to plot texts, it’s easy.
import matplotlib.pyplot as pltfig = plt.figure(figsize=(15,15))
ax=fig.add_subplot(1,1,1)
ax.set_xlim(25, 30)
ax.set_ylim(60, 120)for i, record in records.iterrows():
ax.text(record.Age, record.Win, record.Team, fontsize=40)plt.title('NL West Age/Win Correlation')
plt.show()
If you’d like to plot images of team logo instead of texts, how can we do that? Use “add_artist”, just like this.
from matplotlib.offsetbox import OffsetImage, AnnotationBboxfor i, record in records.iterrows():
image = plt.imread('image/' + record.Team + '.png')
ax.add_artist( #ax can be added image as artist.
AnnotationBbox(
OffsetImage(image)
, (record.Age, record.Win)
, frameon=False
)
)
It’s all done… wait, texts are all behind images! Maybe, if you add texts after adding images, texts are put in front of images.
fig = plt.figure(figsize=(15,15))
ax=fig.add_subplot(1,1,1)
ax.set_xlim(20, 35)
ax.set_ylim(60, 120)
for i, record in records.iterrows():
image = plt.imread('image/' + record.Team + '.png')
ax.add_artist( #ax can be added image as artist.
AnnotationBbox(
OffsetImage(image)
, (record.Age, record.Win)
, frameon=False
)
)
ax.text(record.Age, record.Win, record.Team, fontsize=40)plt.title('NL West Age/Win Correlation')
plt.show()
It’s definitely the same result. How can we do that? The answer is using “add_artist”, either.
import matplotlib.text as mpl_textfig = plt.figure(figsize=(15,15))
ax=fig.add_subplot(1,1,1)
ax.set_xlim(20, 35)
ax.set_ylim(60, 120)
for i, record in records.iterrows():
image = plt.imread('image/' + record.Team + '.png')
ax.add_artist( #ax can be added image as artist.
AnnotationBbox(
OffsetImage(image)
, (record.Age, record.Win)
, frameon=False
)
)
ax.add_artist(
mpl_text.Text(
x=record.Age
,y=record.Win
,text=record.Team
,color='black'
,backgroundcolor='grey'
,verticalalignment='center'
,horizontalalignment='center'
,multialignment=None
,fontsize=40
,linespacing=None
,rotation_mode=None
)
)plt.title('NL West Age/Win Correlation')
plt.show()
It’s all done, eventually!! Just like these, you can add images and texts on graphs of matplotlib using “add_artist”.
I want you to try this!! Thanks for reading.