How do you draw two lines in python?
Matplotlib Basic: Exercise-5 with SolutionWrite a Python program to plot two or more lines on same plot with suitable legends of each line. Show
Sample Solution: Python Code:
Sample Output: Python Code Editor: Contribute your code and comments through Disqus. Previous: Write a Python program to draw line charts of the financial data
of Alphabet Inc. between October 3, 2016 to October 7, 2016. In this Python tutorial, we will discuss, How to plot multiple lines using matplotlib in Python, and we shall also cover the following topics:
Python plot multiple lines on same graphPython provides the Matplotlib library, the most commonly used package for data visualization. It provides a wide variety of plots, tools, and extended libraries for effective data visualization. You can create 2D and 3D plots of the data from different sources like lists, arrays, Dataframe, and external files (CSV, JSON, etc.). It provides an API (or simply a submodule) called pyplot that contains different types of plots, figures, and related functions to visualize data. A line chart is a type of chart/graph that shows the relationship between two quantities on an X-Y plane. You can also plot more than one line on the same chart/graph using matplotlib in python. You can do so, by following the given steps:
Let’s plot a simple graph containing two lines in python. So, open up your IPython shell or Jupiter notebook, and follow the code below:
Python plot multiple lines on the same graphIn the above example, the data is prepared as lists as x, y, z. Then matplot.pyplot.plot() function is called twice with different x, y parameters to plot two different lines. At the end, matplot.pyplot.show() function is called to display the graph containing the properties defined before the function. Read: How to install matplotlib Python plot multiple lines of different colorYou can specify the color of the lines in the chart in python using matplotlib. You have to specify the value for the parameter color in the plot() function of matplotlib.pyplot. There are various colors available in python. You can either specify the color by their name or code or hex code enclosed in quotes. You can specify the color parameter as a positional argument (eg., ‘c’ –> means cyan color; ‘y’ –> means yellow color) or as keyword argument (eg., color=’r’ –> means red color; color=’green’; color=’#B026FF’ –> means neon purple color). Python plot multiple lines of different colorRead: Matplotlib plot a line Python plot multiple lines with legendYou can add a legend to the graph for differentiating multiple lines in the graph in python using matplotlib by adding the parameter label in the matplotlib.pyplot.plot() function specifying the name given to the line for its identity. After plotting all the lines, before displaying the graph, call matplotlib.pyplot.legend() method, which will add the legend to the graph. Python plot multiple lines with a legendPython plot multiple lines from arrayYou can plot multiple lines from the data provided by an array in python using matplotlib. You can do it by specifying different columns of the array as the x and y-axis parameters in the matplotlib.pyplot.plot() function. You can select columns by slicing of the array. Let’s first prepare the data for the example. Create an array using the numpy.array() function. In the below example, a 2D list is passed to the numpy.array() function. Python create 2D arrayNow, plot multiple lines representing the relationship of the 1st column with the other columns of the array. Python plot multiple lines from an arrayRead: What is NumPy Python plot multiple lines from dataframeYou can plot multiple lines from the data provided by a Dataframe in python using matplotlib. You can do it by specifying different columns of the dataframe as the x and y-axis parameters in the matplotlib.pyplot.plot() function. You can select columns by slicing the dataframe. Let’s prepare the data for the example. Create a dataframe using the pandas.DataFrame() function of pandas library. In the below example, a 2D list is passed to the pandas.DataFrame() function, and column names has been renamed to ‘x’, ‘y’, ‘z’. Python Create Dataframe using a 2D listNow, plot multiple lines using the matplotlib.pyplot.plot() function. Python plot multiple lines from dataframeRead: Python NumPy Array If there is a case where, there are several lines that have to be plotted on the same graph from a data source (array, Dataframe, CSV file, etc.), then it becomes time-consuming to separately plot the lines using matplotlib.pyplot.plot() function. So, in such cases, you can use a for loop to plot the number of lines by using the matplotlib.pyplotlib.plot() function only once inside the loop, where x and y-axis parameters are not fixed but dependent on the loop counter. Let’s prepare the data for the example, here a Dataframe is created with 4 columns and 7 rows. Python Create Dataframe using an n-dimensional listIn the code below, the loop counter iterates over the column list of the Dataframe df. And 3 lines are plotted on the graph representing the relationship of the 1st column with the other 3 columns of the Dataframe. Python plot multiple lines for loopRead: Matplotlib best fit line Python plot multiple lines with different y axisThere are some cases where the values of different data to be plotted on the same graph differ hugely and the line with smaller data values doesn’t show its actual trend as the graph sets the scale of the bigger data. To resolve this issue you can use different scales for the different lines and you can do it by using twinx() function of the axes of the figure, which is one of the two objects returned by the matplotlib.pyplot.subplots() function. Let’s make the concept more clear by practicing a simple example: First, prepare data for the example. Create a Dataframe using a dictionary in python containing the population density (per kmsq) and area 100kmsq of some of 20 countries. Python Create Dataframe using dictionaryLet’s plot the data conventionally without separate scaling for the lines. You can see that the Area line is not showing any identical trend with the data as the scale of the Area is very small comparatively from the Population Density. Python plot multiple lines without a different y-axis
Now, let’s plot the lines with different y-axis having different scales using the twinx() function of the axes. You can also set the color and fontsize of the different y-axis labels. Now, you can see some identical trend of all the lines with the data. Python plot multiple lines with the different y-axisRead: Matplotlib subplot tutorial Python plot multiple lines time seriesTime series is the collection of data values listed or indexed in order of time. It is the data taken at some successive interval of time like stock data, company’s sales data, climate data, etc., This type of data is commonly used and needed for the analysis purpose. You can plot multiple lines showing trends of different parameters in a time series data in python using matplotlib. Let’s import a dataset showing the sales details of a company over 8 years ( 2010 to 2017), you can use any time-series data set. After importing the dataset, convert the date-time column (Here, ‘Date’) to the datestamp data type and sort it in ascending order by the ‘Date’ column. Set the ‘Date’ column as the index to make the data easier to plot. Importing CSV file in pythonYou can plot the time series data with indexed datetime by either of the two methods given below. By using the matplotlib.pyplot.plot() function in a loop or by directly plotting the graph with multiple lines from indexed time series data using the plot() function in the pandas.DataFrame. In the code below, the value of the ‘figure.figsize’ parameter in rcParams parameter list is set to (15, 9) to set the figure size global to avoid setting it again and again in different graphs. You can follow any of the two methods given below:
Python plot multiple lines time seriesRead: Matplotlib plot bar chart Python plot multiple lines in 3DYou can plot multiple lines in 3D in python using matplotlib and by importing the mplot3d submodule from the module mpl_toolkits, an external toolkit for matplotlib in python used to plot the multi-vectors of geometric algebra. Let’s do a simple example to understand the concept clearly. First, import the mplot3d submodule then set the projection in matplotlib.axes as ‘3d’. Prepare some sample data, and then plot the data in the graph using matplotlib.pyplot.plot() as same as done in plotting multiple lines in 2d. Python plot multiple lines in 3DRead: Matplotlib time series plot Matplotlib plot multiple lines with same colorIn matplotlib, you can specify the color of the lines in the line charts. For this, you have to specify the value of the color parameter in the plot() function of the matplotlib.pyplot module. In Python, we have a wide range of hues i.e. colors. You can define the color by name, code, or hex code enclosed by quotations. The color parameter can be specified as a keyword argument (e.g., color=’k’ –> means black color; color=’blue’; color=’#DC143C’ –> means crimson color) or as a positional argument (e.g., ‘r’ –> means red color; ‘g’ –> means green color). Let’s have a look at examples where we specify the same colors for multiple lines: Example #1 Here we plot multiple lines having the same color using positional argument.
Example #2 Here we plot multiple lines having the same color using hex code.
Example #3 Here we plot multiple lines having the same color using keyword argument.
Example #4 In matplotlib, using the keyword argument, we plot multiple lines of the same color.
Read: Matplotlib update plot in loop Matplotlib plot title multiple linesHere we’ll learn to add a title to multiple lines chart using matplotlib with the help of examples. In matplotlib, we have two ways to add a title to a plot. The first way is when we want to add a single or main title to the plots or subplots, then we use suptitle() function of pyplot module. And the second way is when we want to add different titles to each plot or subplot, then we use the title() function of pyplot module. Let’s see different examples: Example #1 In this example, we’ll learn to add the main title to multiple lines plot.
Example #2 In this example, we’ll learn to add title to multiple lines plot.
Example #3 In this example, we’ll add the title in multiple lines.
Read: Matplotlib Pie Chart Tutorial Matplotlib plot multiple lines in subplotIn matplotlib, to plot a subplot, use the subplot() function. The subplot() function requires three arguments, each one describes the figure’s arrangement. The first and second arguments, respectively, indicate rows and columns in the layout. The current plot’s index is represented by the third argument. Let’s see examples of a subplot having multiple lines: Example #1 In the above example, we use the subplot() function to create subplots.
Example #2 Let’s see one more example, to create subplots with multiple lines.
Read: Matplotlib scatter plot color Matplotlib plot multiple lines different lengthIn Matplotlib, we’ll learn to plot multiple lines having different lengths with the help of examples. Let’s see examples related to this: Example #1 In this example, we’ll use the axhline() method to plot multiple lines with different lengths and with the same color.
Example #2 In this example, we’ll use the hlines() method to plot multiple lines with different lengths and with different colors.
Example #3 In this example, we’ll use the axvline() method to plot multiple lines with different lengths.
Example #4 In this example, we’ll use the vlines() method to plot multiple lines with different lengths.
Example #5 In this example, we’ll use the array() function of numpy to plot multiple lines with different lengths.
Example #6 In this example, we use the range() function to plot multiple lines with different lengths.
Read: Matplotlib Plot NumPy Array Matplotlib plot multiple lines seabornIn matplotlib, you can draw multiple lines using the seaborn lineplot() function. The following is the syntax:
Here x, y, and hue represent x-axis coordinate, y-axis coordinate, and color respectively. Let’s see examples related to this: Example #1
Example #2
Example #3
Read: Matplotlib set_xticklabels
Matplotlib plot multiple lines from csv filesHere we’ll learn how to plot multiple lines from CSV files using matplotlib. To download the dataset click Max_Temp: To understand the concept more clearly, let‘s see different examples:
Source Code: DataFrame
DataFrame
Example #1
Plot multiple lines using matplotlibExample #2 In this example, we draw three multiple lines plots. Matplotlib plot multiple lines by using CSV fileYou may also like to read the following articles.
In this tutorial, we have discussed, How to plot multiple lines using matplotlibin Python, and we have also covered the following topics:
Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile. How do you draw multiple lines in Python?Python plot multiple lines for loop. Python plot multiple lines with different y axis.. Import matplotlib. pyplot library.. To create subplot, use subplots() function.. Next, define data coordinates using range() function to get multiple lines with different lengths.. To plot a line chart, use the plot() function.. Can we plot multiple lines using Python?you can use: fig,ax = plt. subplots(2) then use: ax[0]. plot(x,y1) ax[1]. plot(x,y2) or if you want you can separate your code into two blocks of code.
How do you plot two values in Python?100 XP. Use plt. subplots to create a Figure and Axes objects called fig and ax , respectively.. Plot the carbon dioxide variable in blue using the Axes plot method.. Use the Axes twinx method to create a twin Axes that shares the x-axis.. Plot the relative temperature variable in red on the twin Axes using its plot method.. |