How Can We Help?
Matplotlib allows us to customize almost everything we may think of the plot. One such important aspect is the ability to change the line size in matplotlib. Matplotlib allows both to statically change the line size and dynamically depending on our requirements. This article will explain how to change the line size in matplotlib.
Prerequisite
Before we proceed with the codes, we presume that the reader has sound knowledge of contour plots. We also need some libraries and packages to code. They are namely matplotlib and numpy. In case you haven’t installed them, then follow the following instructions:
- If you are a windows user, then open the PowerShell and run the following commands: pip install matplotlib numpy
- If you are a Linux or a macOS user, then open the bash terminal and run the following commands: pip install matplotlib numpy
Using the Linewidth Attribute
The most common technique to change the line width is using the pyplot module’s linewidth attribute. This attribute is usually passed with the plot function.
It takes float values as the parameters. However, this is optional use. If not specified, then matplotlib internally assigns 1 to its value.
Example (1)
# Import all the required libraries and modules in the code
import matplotlib.pyplot as plt
import numpy as np
# Creating a user-defined function named lim_change
def size_change(x, y1, y2, y3, y4, y5):
# Creating the figure object
fig = plt.figure(figsize=(9, 9))
# Plotting the figure
plt.plot(x, y1, color='orange', linewidth=1)
plt.plot(x, y2, color='green', linewidth=2)
plt.plot(x, y3, color='red', linewidth=3)
plt.plot(x, y4, color='cyan', linewidth=4)
plt.plot(x, y5, color='yellow', linewidth=5)
# Defining the title for the plot
plt.title("Demonstrating how to change line size in matplotlib")
# Defining the label along the x-axis
plt.xlabel("Values of x")
# Defining the label along the y-axis
plt.ylabel("Values of y")
# Displaying the plot
plt.show()
# Creating the main() function
def main():
# Creating the x coordinates of the data points
x = np.arange(0, 10, 0.1)
# Creating the y coordinates of the data points
y1 = x+1
y2 = x+2
y3 = x+3
y4 = x+4
y5 = x+5
# Calling the lim_change function
size_change (x, y1, y2, y3, y4, y5)
# calling the main function
if __name__ == '__main__':
main()
Output:
Explanation:
- First, we imported all the necessary libraries and packages in our code using the import statement. We used the technique of aliasing for convenience in writing our code in the program.
- Next, we created a user-defined function named size_change. The function is a void function, and it takes six arguments. Under this function, we first created the figure object using the figure function of matplotlib. Next, we plotted the figures using the plot function. We called the function five times to plot five different figures.
- We used the title function to create a title for the figure. Next, we defined the labels along the axes using the xlabel and the ylable functions of matplotlib. We used an optional function show to display the figure.
- After the size_change function, we created the main function, which is the driving code of our program. Under this function, we used the numpy library to create the data points for the plot. We used the arange function of the numpy library. This function takes three arguments, namely start, stop and step. The start defines the number with which the iteration should start, the number with which the iteration should stop, and the step defines the iterating step.
- We called the size_change function to plot the graph, and finally, we called the main function using the following lines of codes: if __name__ == ‘main‘: main()
Using lw Attribute to Change Line Thickness
Another similar method to change the line width is using the lw attribute. This is the aliasing name of the linewidth attribute.
Example (2)
# Import all the required libraries and modules in the code
import matplotlib.pyplot as plt
import numpy as np
# Creating a user-defined function named lim_change
def size_change(x, y1, y2, y3, y4, y5):
# Creating the figure object
fig = plt.figure(figsize=(9, 9))
# Plotting the figure
plt.plot(x, y1, color='orange', linewidth=1)
plt.plot(x, y2, color='green', linewidth=2)
plt.plot(x, y3, color='red', linewidth=3)
plt.plot(x, y4, color='cyan', linewidth=4)
plt.plot(x, y5, color='yellow', linewidth=5)
# Defining the title for the plot
plt.title("Demonstrating how to change line size in matplotlib")
# Defining the label along the x-axis
plt.xlabel("Values of x")
# Defining the label along the y-axis
plt.ylabel("Values of y")
# Displaying the plot
plt.show()
# Creating the main() function
def main():
# Creating the x coordinates of the data points
x = np.arange(0, 10, 0.1)
# Creating the y coordinates of the data points
y1 = np.sin(x)
y2 = np.sin(x)*2
y3 = np.sin(x)*3
y4 = np.sin(x)*4
y5 = np.sin(x)*5
# Calling the lim_change function
size_change(x, y1, y2, y3, y4, y5)
# calling the main function
if __name__ == '__main__':
main()
Output:
Dynamic Line Width
Matplotlib also allows us to change the line width dynamically. How to change it strictly depends on us. We can implement our logic for the same. For the following example, we will use a few advanced functions of the numpy array. Feel free to google the functions to understand precisely how the code works. We also printed the variables for a better understanding of the codes and to visualize the plot better.
Example (3)
# Import all the required libraries and modules in the code
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.collections import LineCollection
# Creating a user-defined function named lim_change
def size_change(line):
# Creating the figure object
fig = plt.figure(figsize=(9, 9))
# Creating the axes object
ax = plt.axes()
# Creating a collection
ax.add_collection(line)
# Defining the limit along the x-axis
ax.set_xlim(0, 10)
# Defining the limits along the y axis
ax.set_ylim(-1.1, 100)
# Defining the title for the plot
plt.title("Demonstrating how to change line size in matplotlib")
# Defining the label along the x-axis
plt.xlabel("Values of x")
# Defining the label along the y-axis
plt.ylabel("Values of y")
# Displaying the plot
plt.show()
# Creating the main() function
def main():
# Defining the x coordinates of the data points
x = np.linspace(0, 10, 100)
# Defining the y coordinates of the data points
y = np.power(x, 2)
# Defining the linewidth array
lline_widths = 1+np.array(x)
# Transposing and changing the shape of the matrix
points = np.array([x, y]).T.reshape(-1, 1, 2)
# Pirinting the shape of the points variable
print(f"The shape of the points array is: {points.shape}")
print(f"The points array is: {points[:5]}")
# Changing the shape of the matrix to the desired shape
segments = np.concatenate([points[:-1], points[1:]], axis=1)
# Pirinting the shape of the segments variable
print(f"The shape of the segments array is: {segments.shape}")
print(f"The segments array is: {segments[:5]}")
line = LineCollection(segments, linewidths=line_widths, color='orange')
# Calling the lim_change function
size_change(line)
# calling the main function
if __name__ == '__main__':
main()
Output:
The shape of the points array is: (100, 1, 2)
The points array is: [[[0. 0. ]]
[[0.1010101 0.01020304]]
[[0.2020202 0.04081216]]
[[0.3030303 0.09182736]]
[[0.4040404 0.16324865]]]
The shape of the segments array is: (99, 2, 2)
The segments array is: [[[0. 0. ]
[0.1010101 0.01020304]]
[[0.1010101 0.01020304]
[0.2020202 0.04081216]]
[[0.2020202 0.04081216]
[0.3030303 0.09182736]]
[[0.3030303 0.09182736]
[0.4040404 0.16324865]]
[[0.4040404 0.16324865]
[0.50505051 0.25507601]]]
Explanation:
- First, we imported the matplotlib.pyplot module, numpy library, and the LineCollection function from the collections module of python matplotlib.
- Next, we created a user-defined function named size_change. The function is void and takes only one argument, namely line.
- Under the function, we first created the figure object using the figure function of matplotlib. We defined the size of the figure object to be (9, 9). Next, we created axes object for the plot using the axes function.
- Next, we added the collection of the data points using the add_collection function. We set limits along the axes using the xlim and the ylim functions. We set the title for the figure using the title function of matplotlib. We also defined the labels along the axes using the xlabel, ylable function of matplotlib.
- We created the main function, which is the driving code of the program. Under this function, we created all the data points required to plt the figure. We used the linspace function to create an array. We also created another array named lwidths. We used it later to change the width of the lines dynamically. We created a matrix out of the array to form a matrix of shape (100,1,2).
- Next, we created the segments array. We created a LineCollection object and passed the segments, lwidths, and color attribute to this function.
- We called the size_change function to plot the figure. Next, we called the main function using the following lines of codes: if __name__ == ‘main‘: main()
Using the Iteration to Plot Dynamic Linewidth
We can use the iteration technique to change the line widths with each iteration. This is not a built-in technique or function, so the logic of the code entirely depends on us.
Example (4)
# Import all the required libraries and modules in the code
import matplotlib.pyplot as plt
import numpy as np
# Creating a user-defined function named lim_change
def size_change(x, y):
# Creating the figure object
fig = plt.figure(figsize=(9, 9))
# Plotting the figure
for i in range(10):
plt.plot(x, y+i*0.2, color='yellow', linewidth=i*0.8)
# Defining the title for the plot
plt.title("Demonstrating how to change line width in matplotlib")
# Defining the label along the x-axis
plt.xlabel("Values of x")
# Defining the label along the y-axis
plt.ylabel("Values of y")
# Displaying the plot
plt.show()
# Creating the main() function
def main():
# Creating the x coordinates of the data points
x = np.arange(0, 10, 0.1)
# Creating the y coordinates of the data points
y= np.cos(x)
# Calling the lim_change function
size_change(x, y)
# calling the main function
if __name__ == '__main__':
main()
Output:
Explanation:
- First, we imported the pyplot module and the numpy library using the import statement of python. Next, we created a user-defined function named size_change, a void function. This function takes two arguments named x and y. Under this function, we defined the size of the figure using the figsize attribute of the figure function.
- Next, We performed an iteration 10 times. Under each iteration, we plotted a graph. We changed the line width of the plots with each iteration depending upon the step. The readers can change that as per their choice.
- We passed the color argument to this function to change the color of the plot. We used dynamic linewidth with each iteration.
- Next, we defined the title of the plot using the title function. Next, we define labels along the figure using the xlabel and the ylabel functions. We used the show function to display the figure. However, it is optional to use the show function in Jupyter Notebook.
- Next, we created the main function, which is the driving code of the program. Under the function, we created all the values of the coordinates of the data points for the plot. We called the size_change function with appropriate parameters to plot the figure.
- Finally, we called the main function using the following lines of codes: if __name__ == ‘main‘: main()
Conclusion
In this article, we have learned how to change the linewidth in matplotlib using different methods and functions. We both saw how to change the line width of the lines statically and dynamically.
We recommend that the readers try to use the line width themselves, especially the dynamic line width part, to understand the concept better. Additionally, we recommend that the readers look up the python matplotlib documentation to understand the topic more.