Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

matplotlib
python
graph
figure

# What is matplotlib? Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The matplotlib Python library, developed by John Hunter and many other contributors, is used to create high-quality graphs, charts, and figures. The library is extensive and capable of changing very minute details of a figure. Some basic concepts and functions provided in matplotlib are:

## 1. Figure and axes

The entire illustration is called a figure and each plot on it is an axes (do not confuse Axes with Axis). The figure can be thought of as a canvas on which several plots can be drawn. We obtain the figure and the axes using the subplots() function:

import matplotlib.pyplot as plt
fig, ax = plt.subplots()

## 2. Plotting

The very first thing required to plot a graph is data. A dictionary of key-value pairs can be declared, with keys and values as the x and y values. After that, ​scatter(), bar(), and pie(), along with tons of other functions, can be used to create the plot:

# Create data:
data = {
"France": 65.4,
"Germany": 82.4,
"Italy": 59.2,
"UK": 66.9
}

# Use keys and values as x and y axis values:
x_axis_data = data.keys()
y_axis_data = data.values()

# Plotting a bar graph:
ax.bar(x_axis_data, y_axis_data)

## 3. Axis

The figure and axes obtained ​using subplots() can be used for modification. Properties of the x-axis and y-axis (labels, minimum and maximum values, etc.) can be changed using Axes.set():

# Setting properties of axes:
ax.set(ylim=[0, 100],
ylabel='Population (in million)',
xlabel='Country',
title='European Countries by Population') Some properties of a plot.

Lastly, pyplot.show() is used to display the graph.

## Code

The following code demonstrates all of the points discussed above:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

# Create data:
data = {
"France": 65.4,
"Germany": 82.4,
"Italy": 59.2,
"UK": 66.9
}

# Use keys and values as x and y axis values:
x_axis_data = data.keys()
y_axis_data = data.values()

# Plotting a bar graph:
ax.bar(x_axis_data, y_axis_data)

# Setting properties of axes:
ax.set(ylim=[0, 100],
ylabel='Population (in million)',
xlabel='Country',
title='European Countries by Population')

# Displaying the graph:
plt.show()

RELATED TAGS

matplotlib
python
graph
figure 