Python

Matplotlib plot multiple lines

The Matplotlib module, the most widely utilized library for visual analytics, is accessible in Python. It offers many charts, methods, and comprehensive frameworks for efficient data analysis. We could make 2D and 3D visualizations of data sets from various domains, including sets, arrays, and Numeric values.

It has a sub module termed pyplot, and it offers several forms of graphs, illustrations, and associated components for data visualization. A line plot is a graph that depicts the relationship between two independent variables on an X-Y axis. We are going to discuss the methods to display different lines utilizing matplotlib in this tutorial.

Using Multiple Patterns of lines to visualize different Lines:

With the aid of matplotlib, we can even design and create many lines with different line patterns. Unique line styles might be involved in the effectiveness of visualizing the data.

import matplotlib.pyplot as plt
import numpy as np
a = [2,4,6,8,10]
b = [8,8,8,8,8]
plt.plot(a, b, label = "First line", linestyle="-.")
plt.plot(b, a, label = "Second line", linestyle="-")
plt.plot(a, np.sin(a), label = "Third line", linestyle=":")
plt.plot(b, np.cos(a), label = "Fourth line", linestyle="--")
plt.legend()
plt.show()

At the beginning of the code, we just import two libraries matplotlib.pyplot as plt and a numerical package for python named numpy as np. We’ll require two entries as data, each having two separate variables (a and b), before presenting the lines as distinct constructs and parameters for the same datasets.

Furthermore, we will utilize the plt.plot() function to generate several lines. There are four parameters involved in these functions. The first parameter of the function contains the first dataset to create the line. Another dataset is also provided as a parameter. We use the ‘label’ argument to specify different tags of the lines drawn.

In addition to this, we have to state different patterns for the lines. In this example, we employ ‘-‘, ‘—‘, ‘-.’, and ‘:’ line styles. We apply the plt.legend() function. Legend() is a method in the matplotlib library that would be used to insert a tag on the planes. Plt.show() function is applied to visualize the plot.

Multiple lines are drawn with a legend in Python:

By providing the label given to the lines because of its identification in the matplotlib.pyplot.plot() method, we will add a label to the chart for distinguishing numerous lines in the plot in python with matplotlib.

import matplotlib.pyplot as plt
a1 = [150,250,350]
b1 = [250,100,350]

plt.plot(a1, b1, label = "First line")
a2 = [100,200,300]
b2 = [200,100,300]
plt.plot(a2, b2, label = "Second line")
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Figure')
plt.legend()
plt.show()

Here we must integrate the matplotlib package before starting the code. For defining the points of the first line, we declare two different variables, ‘a1’ and ‘b1’. Now we have to plot these points, so we call the plt.plot() function for the first line. This function holds three arguments: the points of the x-axis and y-axis, and the ‘label’ parameter shows the caption of the first line.

Similarly, we define datasets for this line. These datasets are stored in two separate variables. For plotting the datasets of the second line, the plt.plot() function is defined. Inside this function, we specified the tag for the second line.

Now we employ two separate functions for defining the label of both the x-axis and y-axis accordingly. We also set the label of the plot by calling the plt.title() function. Just before presenting the plot, we execute the matplotlib.pyplot.legend() function, which would add the caption to the figure since all the lines are displayed.

Draw different plot lines having distinct scales:

We often have two sets of data appropriate for lines of the graphs; however, their data points are drastically different, and making a comparison between these two lines is difficult. We draw the exponential sequence along a log scale in this step, which could result in a relatively horizontal line because the Y-scale will expand gradually.

import matplotlib.pyplot as plt
import numpy as np

linear_sequence = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
exponential_sequence = np.exp(np.linspace(0, 20, 20))
fig, ax = plt.subplots()
ax.plot(linear_sequence, color='black')
ax.tick_params(axis='y', labelcolor='black')
ax1 = ax.twinx()
ax1.plot(exponential_sequence, color='blue')
ax1.set_yscale('log')
ax1.tick_params(axis='y', labelcolor='blue')
plt.show()

In this instance, let’s develop an exponentially growing series of numbers with Numpy, then display that one series next to the other sequence along the same Axes, sequentially. We defined different values for both the linear_sequence dataset and exponential_sequence dataset.

We have to draw the line of the points for linear sequence by calling the ax.plot() method. And we also specified the coloring of the tick captions to black color. For this purpose, we define the function ax.tick_params(). The ax.twinx() method is called to develop a new axes line located in the same position.

Similarly, we draw the line for exponential sequence, and we also define the color of this line and its label. If the first line contains a progressively expanding series of values and the second line has a linearly increasing series of numbers, the first line may have much greater numbers than the second line.

We’ve additionally updated the hue of the tick titles to change the hue of the line plots; else, it’d be tough to predict whichever line is on which axis.

Different lines are displayed in Python by a dataframe:

In Python, we could also utilize matplotlib to create different lines within the same graph by data obtained by a Dataframe. We will accomplish this by using the matplotlib.pyplot.plot() method to define multiple values from the dataframe as the x-axis and y-axis arguments. By splitting the dataframe, we will also specify elements.

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
df = pd.DataFrame([[8, 6, 4], [11, 15, 6], [20, 13, 17],
                   [27, 22, 19], [33, 35, 16], [40, 25, 28],
                   [50, 36, 30]])

df.rename(columns={0: 'a', 1: 'b', 2: 'c'}, inplace=True)
print(np.shape(df), type(df), df, sep='\n')

plt.plot(df['a'], df['b'], color='b', label='first line')
plt.plot(df['a'], df['c'], color='g', label='second line')
plt.legend()
plt.show()

We acquire the packages that are required in this instance. For a visual representation, we employ pyplot from matplotlib, numpy for data collection and processing, and pandas for indicating the data set. Now we will get the data for this scenario. So we develop a dataframe to specify the numeric value that needs to be represented.

We initialize a 2D array, and it is provided to the pandas’ library here. We call the df.rename() function and the component labels are being modified to ‘x’, ‘y’, and ‘z’. In addition to this, we define the functions to display the lines on the plot. Hence, we organize the data and add the graph attributes that we want to be in the plot. The attribute ‘color’ and ‘label’ is provided to the plt.plot() function. In the end, we represent the figure.

Conclusion:

In this article, we observed how to utilize Matplotlib to show many lines on the same graph or dimensions. We’ve talked about how to display the lines within the same Axes having multiple scales, how to display lines with labels, and display lines in a figure with a dataframe.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content