In this tutorial, we will dive into our plotting knowledge and discuss how we can create a line plot using Plotly Express module.
Plotly.express.line()
To create a line plot using the Plotly express module, we will use the line function. The function takes a syntax as shown below:
Despite the large parameter list, the function is relatively simple and rarely will you need to use all the parameters, if any.
Let us explore the most useful and common parameter list you will need to know.
- Data_frame –specifies the column names used in the plot. You can pass these values as a Pandas DataFrame, an array_like object, or a Python dictionary.
- x – specifies the values used to position the marks along the x axis. You can specify this parameter as a column name within the specified data frame, a Pandas series, or an array_like object.
- Y – similar to x but the values are used for the y axis.
- Color – specifies the values used to assign the color to marks.
- Line_group – allows you to group rows of data_frames into lines.
- Line_shape – specifies the shape of the lines. Accepted values include ‘linear’ or ‘spline’.
- Title – specifies the title for the plot.
- Mode – specifies the function will return the Line plot as graph_objects.Figure type.
Line Plot with Plotly.Express Module
Let us now learn how we can create a line plot with plotly express. Take the code shown below:
df = px.data.stocks()
fig = px.line(df, x='date', y='AMZN')
fig.show()
In the example above, we start by importing the plotly express module as px. We then create a DataFrame from the pandas stocks data.
Finally, we create the line plot for the ‘AMZN’ column from the data Frame. The code above should return a time-series chart of the stocks in the data frame.
An example figure is as shown:
Simple Line Plot
We can also create simple line plots without using custom data. For example, we can use a simple NumPy range as shown in the code below.
import numpy as np
x = np.arange(50)
y = np.arange(25, 75)
fig = px.line(x=x, y=y)
fig.show()
The code above should return a simple line plot as shown:
Specifying Color
If you have multiple line plots, you can distinguish them by giving a color using the color parameter.
Take the example code below:
df = px.data.gapminder().query("continent=='Europe'")
fig = px.line(df, x='year', y='lifeExp', color='country')
fig.show()
In this example, we are using the gapminder data. We then create a line plot for each country in the Europe continent. Using the color parameter, we specify the color as country column. This will assign a unique color for each color in the plot.
The resulting figure is as shown:
Congratulations, you have successfully learned how to create and use line plots using Plotly Express.