Introduction to pyplot figure in matplotlib
matplotlib.pyplot
is a sub-library of Python's matplotlib library that provides convenient ways to create static, animated, and interactive visualizations in Python. The pyplot module provides a procedural interface to the object-oriented plotting library matplotlib. This is closely related to Matlab's plotting functions.
The figure()
function in pyplot
creates a new figure and assigns it a number. By default, figures are created with a default size and resolution, but these can be changed with the figsize
and dpi
arguments respectively.
Once a character is created, you can add data to it using various functions such as plot()
, scatter()
, hist()
, etc. You can also add labels and titles to axes and entire figures using functions such as xlabel()
, ylabel()
, and title()
. You can also customize the appearance of your figure using functions such as xlim()
, ylim()
, and grid()
, legend()
, etc.
Additionally, you can create multiple plots in a single figure using the subplots()
function. You can also adjust the spacing between plots using subplots_adjust()
.
Using matplotlib.pyplot library to create figures and plots
You can use the figure()
function to create a new figure and assign it to a variable. Then you can use various functions such as plot()
, scatter()
, and hist()
to add data to the figure. You can also use xlabel()
, ylabel()
, and title()
to add labels to the x-axis, y-axis, and overall title of the plot, respectively. Additionally, you can use xlim()
and ylim()
to set the limits of the x-axis and y-axis, respectively.
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [2, 4, 6, 8]
# Create a figure and axes
fig, ax = plt.subplots()
# Plot the data
ax.plot(x, y)
# Set the x and y axis labels
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
# Show the plot
plt.show()
Output:
Example-1: Create Line Plot
This creates a simple line plot of the x and y values. The plot()
function is used to create the line plot and the xlabel()
, ylabel()
, and title()
functions are used to add labels to the x-axis, y-axis, and overall title of the plot, respectively.
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [2, 4, 6, 8]
plt.plot(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Line Plot')
plt.show()
Output:
Example-2: Create Scatter Plot
This creates a scatter plot of the x and y values. The scatter()
function is used to create the scatter plot and the xlabel()
, ylabel()
, and title()
functions are used to add labels to the x-axis, y-axis, and overall title of the plot, respectively.
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [2, 4, 6, 8]
plt.scatter(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Scatter Plot')
plt.show()
Output:
Example-3: Create Bar Plot
This creates a bar plot of the x and y values. The bar()
function is used to create the bar plot and the xlabel()
, ylabel()
, and title()
functions are used to add labels to the x-axis, y-axis, and overall title of the plot, respectively.
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [2, 4, 6, 8]
plt.bar(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Bar Plot')
plt.show()
Output:
Example-4: Create Multiple plots in a single figure
This creates a 2x2 grid of plots, with a line plot, scatter plot, bar plot, and histogram in each of the four subplots. The subplots()
function is used to create the multiple plots and the plot()
, scatter()
, bar()
, and hist()
functions are used to add data to each of the subplots, respectively.
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [2, 4, 6, 8]
fig, axs = plt.subplots(2, 2)
axs[0, 0].plot(x, y)
axs[0, 1].scatter(x, y)
axs[1, 0].bar(x, y)
axs[1, 1].hist(y)
plt.show()
Output:
Example-5: Define figsize
with figure()
function
In matplotlib.pyplot
, the figure()
function creates a new figure and assigns it a number. By default, the figure will be created with the default size and resolution, but you can modify these using the figsize
and dpi
arguments respectively.
figsize
argument is a tuple of width, height in inches and dpi
argument is the resolution of the figure in dots per inches.
Here is an example of how to use the figsize
argument to create a figure with a specific size:
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [2, 4, 6, 8]
fig = plt.figure(figsize=(4, 3))
plt.plot(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Line Plot')
plt.show()
Output:
Example-6: Add title to pyplot figures
In matplotlib, the pyplot
module provides a simple way to create and manipulate figures and plots. To add a title to a figure, you can use the title()
function, which takes a string argument for the title text.
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4])
plt.title("My Figure Title")
plt.show()
Output:
Example-7: Using add_subplot()
with pypot
module
In matplotlib, the pyplot
module's add_subplot()
function can be used to add one or more subplots to a figure. The basic syntax for add_subplot()
is:
add_subplot(nrows, ncols, plot_number)
Where nrows
and ncols
are the number of rows and columns of subplots in the figure, and plot_number
is the subplot that you want to create, counting from the left to right and top to bottom.
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(2, 2, 1)
ax2 = fig.add_subplot(2, 2, 2)
ax3 = fig.add_subplot(2, 2, 3)
plt.show()
This will create a 2x2 grid of subplots and return the subplot objects as ax1
, ax2
, and ax3
. You can then use these subplot objects to plot data, set labels, etc.
You can also use the subplots()
function to create multiple subplots in one step.
fig, axs = plt.subplots(nrows, ncols)
Here is an example:
nrows = 2
ncols = 2
fig, axs = plt.subplots(nrows, ncols)
This will create a figure with a 2x2 grid of subplots.
Example-8: Change background color of pyplot figure
In matplotlib, we can change the background color of a figure is by using the set_facecolor()
method of the figure
object. This method takes a string argument for the color, which can be specified in a variety of ways, such as by its name (e.g., "white"), by its RGB value (e.g., (1, 1, 1) for white), or by its hex code (e.g., "#FFFFFF
" for white).
import matplotlib.pyplot as plt
fig = plt.figure()
fig.set_facecolor('lightblue')
plt.show()
Output:
Example-9: Modify the axis limit of pyplot figure
In matplotlib, the pyplot
module provides several ways to manipulate the axis of a figure.
One way to control the axis of a figure is by using the xlim()
and ylim()
functions, which can be used to set the limits of the x
and y
axis, respectively. For example:
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4])
plt.xlim(0, 5)
plt.ylim(0, 5)
plt.show()
Output:
We can also control the axis of a figure by using the gca()
function (get current axis) which returns the current axis of the figure and allows to apply methods to it. For example:
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4])
ax = plt.gca()
ax.set_xticks([0, 1, 2, 3, 4])
ax.set_yticks([0, 1, 2, 3, 4])
plt.show()
This will create a simple line plot and set the x-axis ticks to [0, 1, 2, 3, 4]
and y-axis ticks to [0, 1, 2, 3, 4]
.
In case of subplots, these functions can be applied to individual subplots by passing the subplot object as an argument. For example:
fig, axs = plt.subplots(nrows, ncols)
axs[0,0].set_xlim(0,5)
This will set the x-axis limit of the first subplot (top left) to range from 0 to 5.
Example-10: Add labels to axis of pyplot figure
You can also use the xlabel()
and ylabel()
functions to add labels to the x and y axis, respectively. For example:
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4])
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()
This will create a simple line plot and add labels "X-axis" and "Y-axis" to the x and y axis, respectively.
Example-11: Add legend to pyplot figure
In matplotlib, the pyplot
module provides several ways to add a legend to a figure.
One way to add a legend to a figure is by using the legend()
function. For example:
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4], label='Line 1')
plt.plot([4, 3, 2, 1], label='Line 2')
plt.legend()
plt.show()
This will create a simple line plot with two lines, and a legend that shows the label of each line. By default, the legend will be placed in the best location (upper left).
You can also specify the location of the legend using the loc
parameter, which takes an integer or string argument. For example:
plt.legend(loc='upper right')
In case of subplots, the legend()
function can be applied to individual subplots by passing the subplot object as an argument. For example:
fig, axs = plt.subplots(nrows, ncols)
axs[0,0].plot([1, 2, 3, 4], label='Line 1')
axs[0,0].legend()
This will add a legend to the first subplot (top left) of the figure.
You can also use the legend()
method of the axes
object, which allows to specify more detailed options for the legend, such as its size, font, and border.
ax.legend(title='legend Title', fontsize='x-large', framealpha=0.3)
This will add a legend to the axes, with a title, fontsize, and transparency.
Note that in order to add a label to the lines on the plot you need to pass the label parameter in the plot function, plt.plot(x, y, label='label')
.
Summary
Matplotlib's pyplot module provides a simple and convenient way to create and manipulate figures and charts in Python. The main features of pyplot are:
plot()
function: This function is used to create line graphs. Takes one or more arrays of x and y values ​​and draws them as lines on the current figure.scatter()
function: This function is used to create scatter plots. Takes one or more arrays of x and y values ​​and plots them as individual points on the current figure.title()
,xlabel()
,ylabel()
functions: These functions are used to add a title, x-axis label, and y-axis label respectively to the current figure.xlim()
,ylim()
function: These functions are used to set thex
andy
axis limits respectively.legend()
function: This function is used to add a legend to the current figure.add_subplot()
function: You can use this function to add one or more subplots to your figure.subplots()
function: You can use this function to create multiple subplots in one step.set_facecolor()
method of the figure object: This method can be used to change the background color of a figure.gca()
function: This function returns the current axis of the figure and allows methods to be applied to it.rcParams
module: You can use the set() function in matplotlib's rcParams module to change the background color of all figures in your script.subplots_adjust()
function: You can use this function to change the background color of the subplots area by setting thehspace
andwspace
arguments.