How to Read Multiple Lines From a File in Python
In this Python tutorial, we will discuss, How toplot multiple lines using matplotlib in Python, and we shall likewise cover the post-obit topics:
- Python plot multiple lines on same graph
- Python plot multiple lines of different color
- Python plot multiple lines with legend
- Python plot multiple lines from array
- Python plot multiple lines from dataframe
- Python plot multiple lines for loop
- Python plot multiple lines with different y centrality
- Python plot multiple lines fourth dimension series
- Python plot multiple lines in 3D
- Matplotlib plot multiple lines with same color.
- Matplotlib plot championship multiple lines
- Matplotlib plot multiple lines in subplot
- Matplotlib plot multiple lines dissimilar length
- Matplotlib plot multiple lines seaborn
- Matplotlib plot multiple lines from csv files
Python plot multiple lines on same graph
Python provides the Matplotlib library, the most commonly used package for data visualization. It provides a wide variety of plots, tools, and extended libraries for constructive information visualization. You tin can create second and 3D plots of the information from different sources like lists, arrays, Dataframe, and external files (CSV, JSON, etc.).
Information technology provides an API (or only a submodule) called pyplot that contains different types of plots, figures, and related functions to visualize data. A line nautical chart is a blazon of chart/graph that shows the relationship between two quantities on an X-Y plane.
You can likewise plot more than than 1 line on the same chart/graph using matplotlib in python. You lot tin exercise and so, by following the given steps:
- Import necessary libraries (pyplot from matplotlib for visualization, numpy for information creation and manipulation, pandas for Dataframe and importing the dataset, etc).
- Defining the information values that has to be visualized (Define 10 and y or array or dataframe).
- Plot the data (multiple lines) and adding the features you lot desire in the plot (title, color pallete, thickness, labels, notation, etc…).
- Testify the plot (graph/chart). Yous tin can also save the plot.
Let'southward plot a uncomplicated graph containing ii lines in python. And so, open up your IPython shell or Jupiter notebook, and follow the code below:
# Importing packages import matplotlib.pyplot equally plt # Define data values x = [7, xiv, 21, 28, 35, 42, 49] y = [5, 12, xix, 21, 31, 27, 35] z = [3, 5, eleven, 20, 15, 29, 31] # Plot a simple line chart plt.plot(10, y) # Plot another line on the same chart/graph plt.plot(ten, z) plt.show()
In the above example, the data is prepared as lists as 10, y, z. So matplot.pyplot.plot() function is called twice with unlike 10, y parameters to plot two different lines. At the stop, matplot.pyplot.bear witness() function is called to brandish the graph containing the properties defined earlier the function.
Read: How to install matplotlib
Python plot multiple lines of different color
You can specify the colour of the lines in the chart in python using matplotlib. Y'all take to specify the value for the parameter colour in the plot() role of matplotlib.pyplot.
There are various colors available in python. You can either specify the color by their proper noun or code or hex code enclosed in quotes.
Y'all can specify the color parameter as a positional statement (eg., 'c' –> means cyan color; 'y' –> means yellowish color) or as keyword argument (eg., color='r' –> means red colour; color='light-green'; color='#B026FF' –> means neon regal color).
# Importing packages import matplotlib.pyplot as plt # Ascertain data values 10 = [7, fourteen, 21, 28, 35, 42, 49] y = [5, 12, 19, 21, 31, 27, 35] z = [3, 5, eleven, 20, 15, 29, 31] # Plot a simple line chart plt.plot(x, y, 'c') # Plot another line on the same chart/graph plt.plot(ten, z, 'y') plt.testify()
Read: Matplotlib plot a line
Python plot multiple lines with legend
Y'all tin can add a legend to the graph for differentiating multiple lines in the graph in python using matplotlib by calculation the parameter label in the matplotlib.pyplot.plot() part specifying the name given to the line for its identity.
After plotting all the lines, before displaying the graph, call matplotlib.pyplot.fable() method, which will add the fable to the graph.
# Importing packages import matplotlib.pyplot as plt # Ascertain data values ten = [7, 14, 21, 28, 35, 42, 49] y = [5, 12, 19, 21, 31, 27, 35] z = [three, 5, eleven, 20, 15, 29, 31] # Plot a simple line nautical chart plt.plot(x, y, 'g', label='Line y') # Plot another line on the aforementioned nautical chart/graph plt.plot(x, z, 'r', label='Line z') plt.legend() plt.show()
Python plot multiple lines from array
You can plot multiple lines from the data provided by an array in python using matplotlib. You tin do it past specifying unlike 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 assortment.
Let's first set the information for the example. Create an array using the numpy.assortment() role. In the below instance, a 2d list is passed to the numpy.array() function.
import numpy equally np # Ascertain data values in array arr = np.assortment([[7, 5, three], [14, 12, 5], [21, 19, 11], [28, 21, 20], [35, 31, xv], [42, 27, 29], [49, 35, 31]]) print(np.shape(arr), blazon(arr), arr, sep='\n')
At present, plot multiple lines representing the relationship of the 1st cavalcade with the other columns of the array.
import matplotlib.pyplot every bit plt # Plot a elementary line chart plt.plot(arr[:, 0], arr[:, 1], 'g', label='Line y') # Plot some other line on the same chart/graph plt.plot(arr[:, 0], arr[:, 2], 'r', label='Line z') plt.fable() plt.show()
Read: What is NumPy
Python plot multiple lines from dataframe
You lot can plot multiple lines from the information provided by a Dataframe in python using matplotlib. Yous can do it past specifying different columns of the dataframe as the ten and y-axis parameters in the matplotlib.pyplot.plot() function. Yous tin select columns by slicing the dataframe.
Let'due south set 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 'ten', 'y', 'z'.
import pandas as pd import numpy as np # Define information values by creating a Dataframe using a n-dimensional list df = pd.DataFrame([[7, five, 3], [14, 12, five], [21, 19, xi], [28, 21, 20], [35, 31, xv], [42, 27, 29], [49, 35, 31]]) df.rename(columns={0: 'x', ane: 'y', ii: 'z'}, inplace=True) print(np.shape(df), type(df), df, sep='\north')
Now, plot multiple lines using the matplotlib.pyplot.plot() office.
import matplotlib.pyplot as plt # Plot a unproblematic line chart plt.plot(df['ten'], df['y'], color='g', label='Line y') # Plot another line on the same nautical chart/graph plt.plot(df['x'], df['z'], color='r', label='Line z') plt.legend() plt.show()
Read: Python NumPy Assortment
Python plot multiple lines for loop
If there is a case where, there are several lines that take to be plotted on the same graph from a data source (assortment, Dataframe, CSV file, etc.), then information technology becomes fourth dimension-consuming to separately plot the lines using matplotlib.pyplot.plot() office.
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 vii rows.
import pandas as pd import numpy equally np # Define information values past creating a Dataframe using a northward-dimensional list df = pd.DataFrame([[7, v, 3, vii], [14, 12, 5, 14], [21, xix, 11, 21], [28, 21, twenty, 28], [35, 31, 15, 35], [42, 27, 29, 42], [49, 35, 31, 49]]) df.rename(columns={0: 'x', 1: 'y', 2: 'z', 3: 'p'}, inplace=Truthful) print(np.shape(df), type(df), df, sep='\n')
In 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 human relationship of the 1st column with the other three columns of the Dataframe.
import matplotlib.pyplot as plt for col in df.columns: if not col == '10': plt.plot(df['x'], df[col], label='Line '+col) plt.legend() plt.bear witness()
Read: Matplotlib best fit line
Python plot multiple lines with dissimilar y centrality
There are some cases where the values of dissimilar data to be plotted on the same graph differ hugely and the line with smaller data values doesn't show its actual tendency as the graph sets the calibration of the bigger data.
To resolve this event you can apply different scales for the different lines and you can do information technology 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 past practicing a unproblematic example:
Offset, set up data for the case. Create a Dataframe using a dictionary in python containing the population density (per kmsq) and area 100kmsq of some of 20 countries.
import pandas every bit pd # Allow's create a Dataframe using lists countries = ['Monaco', 'Singapore', 'Gibraltar', 'Bahrain', 'Malta', 'Maldives', 'Bermuda', 'Sint Maarten', 'Saint Martin', 'Guernsey', 'State of the vatican city', 'Jersey', 'Palestine', 'Mayotte', 'Lebnon', 'Barbados', 'Saint Martin', 'Taiwan', 'Mauritius', 'San Marino'] area = [2, 106, half dozen, 97, 76, 80, 53, 34, 24, 13, 0.49, 86, 94, 16, 17, 3, 2.1, one.8, 8, xiv] pop_density = [19341, 8041, 5620, 2046, 1390, 1719, 1181, 1261, 1254, 2706, 1124.five, 1129, 1108, 1186, 1056, 1067, 1054, 1052, 944, 954] # At present, create a pandas dataframe using above lists df_pop_density = pd.DataFrame( {'Country' : countries, 'Area(100kmsq)' : surface area, 'Population Density(/kmsq)' : pop_density}) df_pop_density
Allow'southward plot the information conventionally without separate scaling for the lines. Yous can see that the Surface area line is not showing any identical trend with the data as the scale of the Area is very small insufficiently from the Population Density.
import matplotlib.pyplot as plt # Creating figure and axis objects using subplots() fig, ax = plt.subplots(figsize=[9, 7]) ax.plot(df_pop_density['State'], df_pop_density['Area(100kmsq)'], marker='o', linewidth=2, characterization='Area') ax.plot(df_pop_density['Country'], df_pop_density['Population Density(/kmsq)'], marker='o', linewidth=ii, linewidth=ii, characterization='Population Density') plt.xticks(rotation=60) ax.set_xlabel('Countries') ax.set_ylabel('Area / Population Density') plt.legend() plt.prove()
Now, let's plot the lines with different y-centrality having different scales using the twinx() function of the axes. You can also set up the colour and fontsize of the different y-axis labels. At present, you lot can encounter some identical trend of all the lines with the data.
# Creating figure and centrality objects using subplots() fig, ax = plt.subplots(figsize=[9, vii]) # Plotting the firts line with ax axes ax.plot(df_pop_density['Country'], df_pop_density['Area(100kmsq)'], colour='b', linewidth=ii, mark='o') plt.xticks(rotation=60) ax.set_xlabel('Countries', fontsize=15) ax.set_ylabel('Expanse', color='blue', fontsize=15) # Create a twin axes ax2 using twinx() function ax2 = ax.twinx() # At present, plot the second line with ax2 axes ax2.plot(df_pop_density['State'], df_pop_density['Population Density(/kmsq)'], color='orange', linewidth=2, mark='o') ax2.set_ylabel('Population Density', color='orangish', fontsize=15) plt.show()
Read: Matplotlib subplot tutorial
Python plot multiple lines time series
Fourth dimension serial is the collection of data values listed or indexed in order of fourth dimension. It is the data taken at some successive interval of time like stock data, company's sales data, climate data, etc., This blazon of information is unremarkably used and needed for the analysis purpose.
You tin 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 lot can use whatsoever fourth dimension-serial information set.
After importing the dataset, catechumen the date-time cavalcade (Here, 'Date') to the datestamp data type and sort it in ascending order by the 'Engagement' column. Set the 'Date' column equally the index to brand the information easier to plot.
import pandas as pd # Importing the dataset using the pandas into Dataframe sales = pd.read_csv('./Data/Sales_records.csv') print(sales.head(), end='\n\northward') # Converting the Appointment column to the datestamp type sales['Date'] = pd.to_datetime(sales['Date']) # Sorting information in ascending order by the appointment sales = sales.sort_values(by='Appointment') # Now, setting the Appointment column as the index of the dataframe sales.set_index('Engagement', inplace=True) # Print the new dataframe and its summary print(sales.head(), sales.describe(), sep='\n\n')
You tin plot the fourth dimension series data with indexed datetime by either of the two methods given below.
By using the matplotlib.pyplot.plot() part in a loop or by straight 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 'effigy.figsize' parameter in rcParams parameter list is gear up to (fifteen, 9) to set the figure size global to avoid setting it again and once more in different graphs. Y'all tin can follow whatever of the 2 methods given below:
import matplotlib.pyplot equally plt # setting the graph size globally plt.rcParams['figure.figsize'] = (15, 9) # No need of this statement for each graph: plt.effigy(figsize=[xv, 9]) for col in sales.columns: plt.plot(sales[col], linewidth=2, characterization=col) plt.xlabel('Date', fontsize=twenty) plt.ylabel('Sales', fontsize=xx) plt.xticks(fontsize=18) plt.yticks(fontsize=18) plt.fable(fontsize=18) # plt.set_cmap('Paired') # You can set the colormap to the graph plt.show() # OR Yous can also plot a timeseries data by the following method sales.plot(colormap='Paired', linewidth=ii, fontsize=18) plt.xlabel('Appointment', fontsize=20) plt.ylabel('Sales', fontsize=20) plt.legend(fontsize=18) plt.prove()
Read: Matplotlib plot bar nautical chart
Python plot multiple lines in 3D
You tin plot multiple lines in 3D in python using matplotlib and by importing the mplot3d submodule from the modulempl_toolkits, an external toolkit for matplotlib in python used to plot the multi-vectors of geometric algebra.
Let'southward do a simple example to empathise the concept clearly. Start, import the mplot3d submodule then set the projection in matplotlib.axes every bit '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 second.
# Importing packages import matplotlib.pyplot as plt import numpy every bit np from mpl_toolkits import mplot3d plt.axes(project='3d') z = np.linspace(0, i, 100) x1 = 3.seven * z y1 = 0.6 * x1 + iii x2 = 0.5 * z y2 = 0.6 * x2 + ii x3 = 0.eight * z y3 = two.1 * x3 plt.plot(x1, y1, z, 'r', linewidth=two, label='Line 1') plt.plot(x2, y2, z, 'g', linewidth=two, label='Line two') plt.plot(x3, y3, z, 'b', linewidth=2, label='Line 3') plt.championship('Plot multiple lines in 3D') plt.legend() plt.show()
Read: Matplotlib time serial plot
Matplotlib plot multiple lines with aforementioned colour
In matplotlib, you lot tin 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() role of the matplotlib.pyplot module.
In Python, we have a wide range of hues i.e. colors. Yous can ascertain the color past name, code, or hex code enclosed by quotations.
The color parameter tin can be specified as a keyword argument (e.g., color='k' –> ways black color; color='blue'; color='#DC143C' –> means carmine colour) or as a positional statement (e.g., 'r' –> means red color; 'g' –> means light-green color).
Let'southward have a look at examples where we specify the same colors for multiple lines:
Example #one
Here nosotros plot multiple lines having the aforementioned colour using positional statement.
# Importing packages import matplotlib.pyplot as plt import numpy as np # Define data values x = range(three, 13) y1 = np.random.randn(x) y2 = np.random.randn(ten)+range(3, thirteen) y3 = np.random.randn(10)+range(21,31) # Plot 1st line plt.plot(x, y1, 'r', linestyle= 'dashed') # Plot 2d line plt.plot(ten, y2, 'r') # Plot 3rd line plt.plot(x, y3, 'r', linestyle = 'dotted') # Display plt.show()
- Import matplotlib.pyplot module for information visualization.
- Import numpy module to define data coordinates.
- To define data coordinates, use the range(), random.randn() functions.
- To plot the line nautical chart, employ the plot() function.
- To ready dissimilar styles for lines, use linestyle parameter.
- To set the same color to multiple lines, use positional arguments such as 'r', 'g'.
Example #2
Here we plot multiple lines having the same color using hex code.
# Import Libraries import matplotlib.pyplot every bit plt import numpy as np # Define Data x = np.random.randint(low = 0, loftier = 60, size = 50) y = np.random.randint(depression = -15, high = 80, size = fifty) # Plot plt.plot(x, color='#EE1289', label='Line ane') plt.plot(y, color='#EE1289', linestyle = ':', label='Line 2') # Legend plt.fable() # Display plt.show()
- Import matplotlib.pyplot module for data visualization.
- Import numpy module to ascertain information coordinates.
- To define data coordinates, apply random.randint() functions and set its everyman, highest value and size also.
- To plot the line chart, use the plot() function.
- To fix dissimilar styles for lines, use linestyle parameter.
- To set the same colour to multiple lines, use hex code.
- To add a legend to the plot, pass label parameter to plot() part, and also use legend() function.
Example #three
Here we plot multiple lines having the same color using keyword argument.
# Import Libraries import matplotlib.pyplot as plt # Define Data ten = [1, 2, 3] y1 = [two, 3, iv] y2 = [5, half dozen, 7] y3 = [1, ii, 3] # Plot plt.plot(x, y1, colour = 'grand') plt.plot(x, y2, color = 'g') plt.plot(x, y3, colour = 'g') # Display plt.show()
- Import matplotlib.pyplot library.
- Next, define data coordinates.
- To plot the line chart, utilize the plot() function.
- To set the same colour to multiple line charts, use keyword argument color and specify the color proper noun in short grade.
Example #4
In matplotlib, using the keyword argument, we plot multiple lines of the same color.
# Import Libraries import matplotlib.pyplot equally plt import numpy as np # Ascertain Data 10 = np.arange(0,half-dozen,0.two) y1 = np.sin(x) y2 = np.cos(x) # Plot plt.plot(x, y1, color ='slategray') plt.plot(x, y2, color = 'slategray') # Display plt.show()
- Import matplotlib.pyplot library.
- Import numpy bundle.
- Next, define data coordinates using arange(), sin() and cos() functions.
- To plot the line chart, use the plot() function.
- To prepare the same color to multiple line charts, use keyword argument color and specify the color name.
Read: Matplotlib update plot in loop
Matplotlib plot title multiple lines
Here we'll learn to add a title to multiple lines chart using matplotlib with the help of examples. In matplotlib, we accept two ways to add together a championship to a plot.
The offset fashion is when we desire to add a single or main title to the plots or subplots, then we use suptitle() office of pyplot module. And the second fashion is when we want to add together different titles to each plot or subplot, then we utilize the championship() office of pyplot module.
Permit's see different examples:
Case #1
In this example, we'll learn to add the chief title to multiple lines plot.
# Import Libraries import matplotlib.pyplot as plt import numpy as np # Define Data x = np.arange(20) y1 = x+8 y2 = 2*x+8 y3 = iv*x+8 y4 = 6*10+8 y5 = 8*x+viii # Colors colors=['lightcoral', 'xanthous', 'lime', 'slategray', 'pinkish'] plt.gca().set_prop_cycle(color=colors) # Plot plt.plot(ten, y1) plt.plot(x, y2) plt.plot(ten, y3) plt.plot(x, y4) plt.plot(x, y5) # Chief Title plt.suptitle("Multiple Lines Plot", fontweight='bold') # Display plt.show()
- Import matplotlib.pyplot package for data visualization.
- Import numpy package for data plotting.
- To define data coordinates, utilise arange() office.
- The matplotlib.axes.Axes.set_prop_cycle() method takes a list of colors to employ in club as an argument.
- To plot multiple line chart, utilize plot() office.
- To add a main title to a plot, utilise suptitle() function.
Example #2
In this instance, we'll learn to add title to multiple lines plot.
# Import Libraries import matplotlib.pyplot every bit plt import numpy as np # Define Data x = np.linspace(0, 8, 100) y1 = v*ten y2 = np.power(x,2) y3 = np.exp(ten/18) # Plot plt.plot(10, y1, colour='coral') plt.plot(10, y2, color='lawngreen') plt.plot(10, y3) # Title plt.title("Multiple Lines Plot", fontweight='bold') # Display plt.show()
- Firstly, import matplotlib.pyplot and numpy libraries.
- To define data coordinates, use linspace(), ability(), and exp() functions.
- To plot a line, use plot() function of pyplot module.
- To add a title to a plot, use title() part.
Example #iii
In this instance, nosotros'll add the title in multiple lines.
# Import Libraries import matplotlib.pyplot every bit plt import numpy every bit np # Define Data 10 = np.arange(0,x,0.2) y1 = np.sin(10) y2 = np.cos(x) # Plot plt.plot(10, y1) plt.plot(x, y2) # Multiple line title plt.suptitle('Plot Multple Lines \n With Multiple Lines Titles', fontweight='bold') # Display plt.bear witness()
- Import matplotlib.pyplot library.
- Import numpy library.
- Next, define information coordinates using arange(), sin(), and cos() functions.
- To plot a line chart, utilize plot() role.
- To add a title in multiple lines, utilize suptitle() role with new line character.
Read: Matplotlib Pie Chart Tutorial
Matplotlib plot multiple lines in subplot
In matplotlib, to plot a subplot, use the subplot() role. The subplot() function requires three arguments, each ane describes the figure'due south organisation.
The first and second arguments, respectively, betoken rows and columns in the layout. The current plot's index is represented by the 3rd argument.
Let'due south encounter examples of a subplot having multiple lines:
Instance #1
In the above example, nosotros apply the subplot() function to create subplots.
# Import Libraries import matplotlib.pyplot equally plt import numpy every bit np # Set figure size plt.figure(figsize=(8,vi)) # plot i: plt.subplot(1, ii, 1) # Data x = np.random.randint(low = 0, loftier = 150, size = xxx) y = np.random.randint(low = 10, high = l, size = 30) # Plotting plt.plot(10) plt.plot(y) # plot 2: plt.subplot(1, 2, 2 ) # Information x = [one, two, 3] y1 = [2, 3, 4] y2 = [5, 6, 7] # Plotting plt.plot(x,y1) plt.plot(ten,y2) # Display plt.show()
- Import matplotlib.pyplot and numpy packages.
- To prepare figure size use figsize and set width and height.
- To plot subplot, use subplot() role with rows, columns and index numbers.
- To define data coordinates, use random.randint() function.
- To plot a line chart, use plot() function.
Example #two
Permit'south come across one more example, to create subplots with multiple lines.
# Import Libraries import matplotlib.pyplot as plt import numpy as np # Fix figure size plt.figure(figsize=(viii,6)) # plot one: plt.subplot(i, 2, 1) # Data x = np.linspace(0, viii, 100) y1 = np.exp(x/18) y2 = 5*x # Plotting plt.plot(x, y1) plt.plot(ten, y2) # plot 2: plt.subplot(one, 2, 2 ) # Information x = np.arange(0,x,0.two) y1 = np.sin(x) y2 = np.cos(x) # Plotting plt.plot(ten,y1) plt.plot(x,y2) # Display plt.bear witness()
- Here nosotros use linspace(), exp(), arange(), sin(), and cos() functions to define information coordinates to plot subplot.
- To plot a line chart, use plot() functions.
Read: Matplotlib besprinkle plot color
Matplotlib plot multiple lines different length
In Matplotlib, we'll learn to plot multiple lines having different lengths with the help of examples.
Permit'due south meet examples related to this:
Example #1
In this example, we'll employ the axhline() method to plot multiple lines with different lengths and with the same color.
# Import library import matplotlib.pyplot equally plt # line i plt.axhline (y = 2) # line 2 plt.axhline (y = three, xmax =0.4) # line iii plt.axhline (y = four, xmin = 0.iv, xmax =0.8) # line 4 plt.axhline (y = 5, xmin =0.25, xmax =0.65) # Line v plt.axhline (y = 6, xmin =0.half-dozen, xmax =0.8) # Display plt.show()
- Import matplotlib.pyplot library.
- Next, we apply the axhline() method to plot multiple lines.
- To prepare unlike lengths of lines we pass xmin and xmax parameters to the method.
- To get lines with the same colour, nosotros tin't specify the color parameter. If you, want different color lines specify color parameter also.
Example #2
In this example, we'll use the hlines() method to plot multiple lines with different lengths and with different colors.
# Import library import matplotlib.pyplot equally plt # line ane plt.hlines (y= 2, xmin= 0.1, xmax= 0.35, color='c') # line two plt.hlines (y= 4, xmin = 0.1, xmax = 0.55, color='m', linestyle = 'dotted') # line 3 plt.hlines (y = 6, xmin = 0.i, xmax = 0.75, color='orange', linestyle = 'dashed') # line iv plt.hlines (y = 8, xmin =0.one, xmax =0.ix, colour='red') # Display plt.show()
- Import matplotlib.pyplot library.
- Next, we use the hlines() method to plot multiple lines.
- To gear up unlike lengths of lines we pass xmin and xmax parameters to the method.
- If you, desire dissimilar colour lines specify color parameter besides.
Example #3
In this instance, we'll utilise the axvline() method to plot multiple lines with unlike lengths.
# Import library import matplotlib.pyplot as plt # line one plt.axvline(x = 5, colour = 'b') # line 2 plt.axvline(x = three, ymin = 0.2, ymax = 0.8, color='red') # line 3 plt.axvline(x = 3.75, ymin = 0.2, ymax = ane, color='lightgreen') # line 4 plt.axvline(ten = 4.50, ymin = 0, ymax = 0.65, colour='1000') # Display plt.show()
- Import matplotlib.pyplot library.
- Adjacent, we use the axvline() method to plot multiple lines.
- To gear up dissimilar lengths of lines nosotros laissez passer ymin and ymax parameters to the method.
- If you, desire different color lines specify color parameter also.
Example #4
In this example, we'll use the vlines() method to plot multiple lines with unlike lengths.
# Import library import matplotlib.pyplot as plt # Vertical line 1 plt.vlines(x = v, ymin = 0.75, ymax = ii, colour = 'black') # Vertical line 2 plt.vlines (x = 8, ymin = 0.50, ymax = 1.v, colour='reddish') # Vertical line 3 plt.vlines (x = [1, 2] , ymin = 0.2, ymax = 0.6, color = 'orange') # Vertical line 4 plt.vlines (x = 10, ymin = 0.two, ymax = 2, color='yellow') # Display plt.show()
- Here we use the axvline() method to plot multiple lines.
- To set dissimilar lengths of lines we laissez passer ymin and ymax parameters to the method.
Example #v
In this example, we'll use the assortment() function of numpy to plot multiple lines with different lengths.
# Import Libraries import matplotlib.pyplot equally plt import numpy as np # Define Data 10 = np.array([2, 4, 6, viii, x, 12]) y = np.array([iii, half-dozen, 9]) # Plot plt.plot(10) plt.plot(y) # Display plt.show()
- Firstly, import matplotlib.pyplot, and numpy libraries.
- Adjacent, define data coordinates using the assortment() method of numpy. Hither nosotros define lines of different lengths.
- To plot a line chart, employ the plot() method.
Example #half dozen
In this example, we use the range() function to plot multiple lines with different lengths.
# Import library import matplotlib.pyplot as plt # Create subplot fig, ax = plt.subplots() # Define Data x = range(2012,2022) y = [10, eleven, 10.five, 15, 16, nineteen, 14.5, 12, 13, 20] x1 = range(2016, 2022) y1 = [11.5, 15.5, xv, sixteen, 20, xi] # Plot ax.plot(10, y, color= '#CD1076') ax.plot(x1,y1, colour = 'orange') # Testify plt.show()
- Import matplotlib.pyplot library.
- To create subplot, use subplots() part.
- Side by side, ascertain data coordinates using range() function to get multiple lines with different lengths.
- To plot a line chart, utilize the plot() office.
Read: Matplotlib Plot NumPy Array
Matplotlib plot multiple lines seaborn
In matplotlib, you can draw multiple lines using the seaborn lineplot() function.
The following is the syntax:
sns.lineplot(x, y, hue)
Hither x, y, and hue represent x-centrality coordinate, y-centrality coordinate, and color respectively.
Let's see examples related to this:
Example #1
# Import Libraries import seaborn as sns import pandas as pd import matplotlib.pyplot as plt # Define Information days = [one, 2, 3, iv, v, six, 7, 8, nine, x, xi, 12, 13, 14, xv] max_temp = [36.6, 37, 37.7, 13, 15.6, 46.eight, 50, 22, 31, 26, xviii, 42, 28, 26, 12] min_temp = [12, 8, 18, 12, eleven, 4, 3, 19, xx, 10, 12, 9, fourteen, nineteen, 16] # Dataframe temp_df = pd.DataFrame({"days":days, "max_temp":max_temp, "min_temp":min_temp}) # Impress temp_df
- Firstly, import necessary libraries such as seaborn, matplotlib.pyplot, and pandas.
- Next, ascertain information.
- To create data frame, use DataFrame() function of pandas.
# Plot seaborn sns.lineplot(x = "days", y = "max_temp", data=temp_df,) sns.lineplot(10 = "days", y = "min_temp", data=temp_df,) # Show plt.show()
- To plot multiple line chart using seaborn package, utilize lineplot() role.
- To display the graph, utilize show() function.
Example #2
# Import Libraries import seaborn as sns import numpy as np import matplotlib.pyplot equally plt # Ascertain Data x = np.linspace (ane,10,two) y = x * 2 z = np.exp(x) # Seaborn Plot sns.lineplot(x = x, y = y) sns.lineplot(x = x, y = z) # Show plt.show()
- Import libraries such every bit seaborn, numpy, and matplotlib.pyplot.
- To ascertain data coordinates, utilize linspace(), exp() functions of numpy.
- To plot seaborn line plot, apply lineplot() function.
- To display the graph, apply show() function.
Case #3
# Import Libraries import matplotlib.pyplot as plt import numpy as np import seaborn equally sns # Set mode sns.set_style("darkgrid") # Define Data x = np.arange(0,20,0.ii) y1 = np.cos(x) y2 = np.sin(ii*x) # Plot sns.lineplot(x = x, y = y1) sns.lineplot(x = x, y = y2) # Display plt.show()
- Import necessary libraries such as, matplotlib.pyplot, numpy, and seaborn.
- Set mode of plot, use set_style() method and set information technology to darkgrid.
- To define data coordinates, utilize arange(), cos(), and sin() functions.
- To plot multiple lines, use lineplot() function.
- To visualize the plot, use show() function.
Read: Matplotlib set_xticklabels
Matplotlib plot multiple lines from csv files
Here we'll learn how to plot multiple lines from CSV files using matplotlib.
To download the dataset click Max_Temp:
To sympathise the concept more than clearly, let'due south see different examples:
- Import necessary libraries such as pandas and matplotlib.pyplot.
- Side by side, read the csv file using read_csv() function of pandas.
- To view the csv file, print information technology.
Source Code:
# Import Libraries import pandas every bit pd import matplotlib.pyplot as plt # Read CSV data= pd.read_csv('Max_Temp.csv') # Print data
- Next, we catechumen the CSV file to the panda'southward data frame, using the DataFrame()function.
- If you lot, want to view the data frame impress it.
# Convert data frame df=pd.DataFrame(data) # Print df
- Past usingiloc() function, initialize the list to select the rows and columns by position from pandas Dataframe.
# Initilaize list days = list(df.iloc[:,0]) city_1 = list(df.iloc[:,one]) city_2 = listing(df.iloc[:,2]) city_3 = list(df.iloc[:,three]) city_4 = listing(df.iloc[:,iv])
Case #1
- Now, gear up the effigy size past usingfigsize() part
- To plot multiple lines chart , use theplot() function and pass the data coordinates.
- To set a marking, passmark as a parameter.
- To visualize the graph, use theprove() function.
# Set Figure Size plt.figure(figsize=(8,6)) # Plot plt.plot(days, city_4, marking='o') plt.plot(days, city_2, marker='o') # Brandish plt.show()
Example #two
In this example, nosotros describe three multiple lines plots.
# Set Effigy Size plt.figure(figsize=(8,6)) # Plot plt.plot(days, city_4, marker='o') plt.plot(days, city_2, mark='o') plt.plot(days, city_1, marker='o') # Display plt.testify()
You may also like to read the following articles.
- What is matplotlib inline
- Matplotlib bar chart labels
- Put legend exterior plot matplotlib
In this tutorial, we accept discussed, How to plot multiple lines using matplotlib in Python, and we have also covered the following topics:
- Python plot multiple lines on aforementioned graph
- Python plot multiple lines of different colour
- Python plot multiple lines with fable
- Python plot multiple lines from array
- Python plot multiple lines from dataframe
- Python plot multiple lines for loop
- Python plot multiple lines with different y axis
- Python plot multiple lines time series
- Python plot multiple lines in 3D
- Matplotlib plot multiple lines with same colour.
- Matplotlib plot championship multiple lines
- Matplotlib plot multiple lines in subplot
- Matplotlib plot multiple lines different length
- Matplotlib plot multiple lines seaborn
- Matplotlib plot multiple lines from csv files
Source: https://pythonguides.com/python-plot-multiple-lines/
0 Response to "How to Read Multiple Lines From a File in Python"
إرسال تعليق