import matplotlib.pyplot as plt
import seaborn as sns
= [0.895, 0.91, 0.919, 0.926, 0.929, 0.931]
yield_maize
plt.plot(yield_maize) plt.show()
Data Visualization Using Matplotlib and Seaborn
Introduction
We explore how to do various visualizations using the matplolib and seaborn libraries in Python.
We shall learn the following in this tutorial:
- The fundamentals of plotting figures
- Creating sub-plots in Python
- Creating animations in Python
To decide which software to use between R
and Python
for data visualization you can watch this video.
Fundamentals of Plots in Python
The first step is to install and import the libraries matplolib.pylot
module that is used for basic plots like line and bar charts. It is often imported with the alias plt
.
We shall use the seaborn
module for more advanced plots that is imported as sns
To install use
!pip install seaborn
on the Jupyter Notebook Environment.
To call the module to the environment use
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
The purpose of the command %matplotlib inline
is to ensure that the plots are shown and embedded within the Jupyter Notebook Itself.
Without the command the plots may sometimes show in pop-up windows.
Line Graph
Customizing the x-axis
We can add the year
in the x-axis and have
= [2021,2022,2023,2024,2025,2026]
year = [0.895, 0.91, 0.919, 0.926, 0.929, 0.931]
yield_maize
plt.plot(year,yield_maize) plt.show()
Axis Labels
plt.plot(year, yield_maize)"Year")
plt.xlabel("Yield")
plt.ylabel("Yield Harvest per year") plt.title(
Text(0.5, 1.0, 'Yield Harvest per year')
Line Markers
For line graphs, you can have markers for the line you are plotting. See full details of line markers in matplotlib
= "o")
plt.plot(year, yield_maize, marker "Year")
plt.xlabel("Yield")
plt.ylabel("Yield Harvest per year") plt.title(
Text(0.5, 1.0, 'Yield Harvest per year')
Styling the Lines
The function plt.plot
supports many arguments for styling markers and the lines
color
orc
This sets the line colorls
Gives you to choose between solid or dashed linelw
sets the line width
To see more details of the function see the documentation
Using Seaborn
To make your chart more appeasing you use some default styles form Seaborn library.
Whitegrid style
"whitegrid")
sns.set_style(= "o")
plt.plot(year, yield_maize, marker "Year")
plt.xlabel("Yield")
plt.ylabel("Yield Harvest per year") plt.title(
Text(0.5, 1.0, 'Yield Harvest per year')
darkgrid style
"darkgrid")
sns.set_style(= "o")
plt.plot(year, yield_maize, marker "Year")
plt.xlabel("Yield")
plt.ylabel("Yield Harvest per year") plt.title(
Text(0.5, 1.0, 'Yield Harvest per year')