Plotly: Plotting and Styling

Faran Mohammad
5 min readJul 11, 2023

--

This is the 2nd part of my Plotly series. If you haven’t read the first one, you can read it here.

Now, we are going to get into the more practical usage of Plotly and how we can use it for Data Visualisation. We are going to use something called plotly.data package from the official Plotly documentation. It contains built-in datasets for demonstration, educational and test purposes.

To start off, we are going to import the graph_objects package.

import plotly.graph_objects as go

This module provides the functionality to create and manipulate different types of graphs.

df_stocks = px.data.stocks()
px.line(df_stocks, x='date', y='GOOG', labels={'x': 'Date', 'y': 'Price'})

This code is using the Plotly library to create a line graph of the stock prices for a specific company, in this case, Google (GOOG).

The first line `df_stocks = px.data.stocks()` creates a DataFrame called `df_stocks` using the `stocks()` function from the `px.data` module. This function returns a sample dataset of stock prices for different companies, including Google (GOOG). The DataFrame contains columns for date and various stock prices.

The main part of the code is `px.line(df_stocks, x=’date’, y=’GOOG’, labels={‘x’: ‘Date’, ‘y’: ‘Price’})`. Here, the `px.line()` function is used to create a line graph.

The `df_stocks` DataFrame is passed as the first argument, specifying the data to be plotted.

The `x=’date’` parameter specifies that the ‘date’ column from the DataFrame should be used as the x-axis values for the graph.

The `y=’GOOG’` parameter indicates that the ‘GOOG’ column from the DataFrame should be used as the y-axis values for the graph. This column contains the stock prices for Google.

The `labels={‘x’: ‘Date’, ‘y’: ‘Price’}` parameter sets the labels for the x-axis and y-axis of the graph, respectively.

Overall, this code generates a line graph showing the historical stock prices for Google (GOOG) over time, with the x-axis representing the dates and the y-axis representing the stock prices.

output of the above code

We can also make multiple different line blocks:

px.line(df_stocks, x='date', y=['GOOG', 'AAPL'], labels={'x': 'Date',
'y': 'Price'}, title='Apple vs Google')

This updated code is similar to the previous code, but it includes an additional feature. It creates a line graph comparing the stock prices of two companies: Google (GOOG) and Apple (AAPL).

Let’s break down the code:

- The `px.line()` function is still used to create a line graph.

- The `df_stocks` DataFrame is passed as the first argument, providing the data for the graph.

- The `x=’date’` parameter specifies that the ‘date’ column from the DataFrame should be used as the x-axis values.

- The `y=[‘GOOG’, ‘AAPL’]` parameter indicates that two columns from the DataFrame, ‘GOOG’ and ‘AAPL’, should be used as the y-axis values. These columns contain the stock prices for Google and Apple, respectively.

- The `labels={‘x’: ‘Date’, ‘y’: ‘Price’}` parameter sets the labels for the x-axis and y-axis of the graph, respectively.

- The `title=’Apple vs Google’` parameter sets the title of the graph as ‘Apple vs Google’.

In summary, this code generates a line graph that compares the historical stock prices of Google and Apple over time. The x-axis represents the dates, the y-axis represents the stock prices, and the graph is titled ‘Apple vs Google’.

output of the above code

Now, moving to the very complex types of graphs, using Figures. To do that,

fig = go.Figure()
fig.add_trace(go.Scatter(x=df_stocks.date, y=df_stocks.AAPL,
mode='lines', name='Apple'))
fig.add_trace(go.Scatter(x=df_stocks.date, y=df_stocks.AMZN,
mode='lines+markers', name='Amazon'))
fig.add_trace(go.Scatter(x=df_stocks.date, y=df_stocks.GOOG,
mode='lines+markers', name='Google',
line=dict(color='firebrick', width=2, dash='dashdot')))

fig.update_layout(title='Stock Price Data 2018-2020', xaxis_title='Price', yaxis_title='Date')

This code creates a line graph using the Plotly library. It adds three traces (lines) to the graph, each representing the stock prices of a different company: Apple, Amazon, and Google.

Let’s break down the code step by step:

fig = go.Figure()

This line initializes an empty Figure object, which will be used to create the graph.

fig.add_trace(go.Scatter(x=df_stocks.date, y=df_stocks.AAPL, mode='lines', name='Apple'))

Here, a new trace is added to the graph using the `add_trace()` method of the Figure object. The `go.Scatter` function creates a trace for a line graph.

- The `x` parameter is set to `df_stocks.date`, which represents the x-axis values, the dates.

- The `y` parameter is set to `df_stocks.AAPL`, which represents the y-axis values, the stock prices of Apple.

- The `mode` parameter is set to `’lines’`, indicating that the data points will be connected with lines.

- The `name` parameter is set to `’Apple’`, providing a label for the trace.

Similarly, two more traces are added for Amazon and Google using the same pattern:

fig.add_trace(go.Scatter(x=df_stocks.date, y=df_stocks.AMZN, mode='lines+markers', name='Amazon'))
fig.add_trace(go.Scatter(x=df_stocks.date, y=df_stocks.GOOG, mode='lines+markers', name='Google', line=dict(color='firebrick', width=2, dash='dashdot')))

After adding the traces, the code updates the layout of the graph:

fig.update_layout(title='Stock Price Data 2018-2020', xaxis_title='Price', yaxis_title='Date')

The `update_layout()` method is used to modify the layout properties of the graph. The `title` parameter sets the title of the graph, while `xaxis_title` and `yaxis_title` set the labels for the x-axis and y-axis, respectively.

In summary, this code creates a line graph with multiple traces, representing the stock prices of Apple, Amazon, and Google over time. Each trace is customized with different line styles, and the graph’s layout is updated with a title and axis labels.

output of the above code

To further, add more styling to the graph,

fig.update_layout(
xaxis=dict(
showline=True,
showgrid=False,
showticklabels=True,
linecolor='rgb(204, 204, 204)',
linewidth=2,
ticks='outside',
tickfont=dict(family='Arial', size=12, color='rgb(82,82,82)'),
),
yaxis=dict(
showgrid=False,
zeroline=False,
showline=False,
showticklabels=False),
autosize=False,
margin=dict(autoexpand=False, l=100, r=20, t=110),
showlegend=False,
plot_bgcolor='white',
)

The updated code modifies the layout of the graph by adjusting various properties using the `update_layout()` method. Let’s go through the changes:

1. `xaxis` and `yaxis` Properties:

- `showline=True` displays the x-axis line.

- `showgrid=False` hides the gridlines on the graph.

- `showticklabels=True` displays the tick labels on the x-axis.

- `linecolor=’rgb(204, 204, 204)’` sets the color of the x-axis line to a light gray.

- `linewidth=2` sets the width of the x-axis line to 2 pixels.

- `ticks=’outside’` positions the ticks outside the graph area.

- `tickfont=dict(family=’Arial’, size=12, color=’rgb(82,82,82)’)` sets the font properties for the x-axis tick labels.

For the y-axis:

- `showgrid=False` hides the gridlines on the y-axis.

- `zeroline=False` hides the zero line on the y-axis.

- `showline=False` hides the y-axis line.

- `showticklabels=False` hides the tick labels on the y-axis.

2. `autosize=False` disables the automatic resizing of the graph.

3. `margin=dict(autoexpand=False, l=100, r=20, t=110)` sets the margins of the graph. `l`, `r`, `t` represent the left, right, and top margins, respectively. The `autoexpand=False` ensures that the margins do not automatically adjust to the content.

4. `showlegend=False` hides the legend of the graph.

5. `plot_bgcolor=’white’` sets the background color of the plot to white.

Overall, these layout modifications adjust the appearance of the graph by controlling the visibility of lines, grids, tick labels, and legends, as well as customizing the margins and background color.

output of the above code

You can find the complete notebook here.

--

--

Faran Mohammad
Faran Mohammad

Written by Faran Mohammad

I am a Software Development Engineer. I like reading and writing about tech. Being a geek, I like to experiment with various technologies and stacks.

No responses yet