Matplotlib
- A Python library for creating static, animated, and interactive visualizations.
- Commonly used to draw line plots, scatter plots, bar charts, histograms, and more.
- Often used together with Pandas to plot data loaded from CSV or other data sources.
Definition
Section titled “Definition”Matplotlib is a powerful Python library used for data visualization. It allows users to create a wide range of static, animated, and interactive visualizations in a variety of formats, including plots, histograms, scatter plots, bar charts, and more.
Explanation
Section titled “Explanation”Matplotlib provides plotting functions (commonly via matplotlib.pyplot aliased as plt) to build visualizations. Typical workflows shown in the examples include:
- Importing
matplotlib.pyplotand setting a plotting style:plt.style.use('seaborn'). - Loading data into a Pandas
DataFrameand extracting relevant columns. - Using plotting functions such as
plot()for line plots andscatter()for scatter plots. - Adding axis labels and titles with
xlabel(),ylabel(), andtitle(). - Rendering the visualization with
show().
Examples
Section titled “Examples”Line plot — Average monthly temperature
Section titled “Line plot — Average monthly temperature”To create a line plot of average monthly temperature:
import matplotlib.pyplot as plt
plt.style.use('seaborn')
import pandas as pd
df = pd.read_csv('temperature_data.csv')
month = df['month']
temperature = df['temperature']
plt.plot(month, temperature)
plt.xlabel('Month')
plt.ylabel('Temperature (°F)')
plt.title('Average Monthly Temperature in City')
plt.show()The resulting line plot will show the trend of the average monthly temperature in the city over the course of a year.
Scatter plot — Height vs Weight
Section titled “Scatter plot — Height vs Weight”To create a scatter plot showing the relationship between height and weight:
import matplotlib.pyplot as plt
plt.style.use('seaborn')
import pandas as pd
df = pd.read_csv('height_weight_data.csv')
height = df['height']
weight = df['weight']
plt.scatter(height, weight)
plt.xlabel('Height (in)')
plt.ylabel('Weight (lb)')
plt.title('Height vs Weight')
plt.show()The resulting scatter plot will show the relationship between height and weight in the group of individuals.
Use cases
Section titled “Use cases”- Data analysts and scientists use Matplotlib to create visualizations that help them understand and analyze their data and communicate their findings to others.
Related terms
Section titled “Related terms”- Pandas
- matplotlib.pyplot (plt)