Line charts#
Documentation:
https://plotly.com/python/line-charts/
The standard line graph:
import plotly.express as px
df_stocks = px.data.stocks()
line_chart = px.line(
data_frame=df_stocks,
x='date',
y='GOOG',
)
line_chart
Multiple lines#
(when each line is a column)
line_chart_multi = px.line(
data_frame=df_stocks,
x='date',
y=['GOOG', 'AMZN', 'MSFT', 'FB', 'AAPL'],
)
line_chart_multi
Markers#
line_w_markers = px.line(
data_frame=df_stocks,
x='date',
y='GOOG',
markers=True,
)
line_w_markers
Line colors#
line_colors = px.line(
data_frame=df_stocks,
x='date',
y=['GOOG', 'AMZN', 'MSFT', 'FB', 'AAPL'],
color_discrete_map=dict(
GOOG='red',
AMZN='green',
MSFT='blue',
FB='black',
AAPL='magenta',
)
)
line_colors
Line styles#
Shaded regions#
Modifying a single line#
A large example#
stock_list = ['GOOG', 'AMZN', 'MSFT', 'FB', 'AAPL']
stock_fig = px.line(
data_frame=df_stocks,
x='date',
y=stock_list,
height=700,
color_discrete_map=dict(
GOOG='DarkGray',
AAPL='DarkGreen',
AMZN='DarkGray',
MSFT='DarkGray',
FB='DarkGray',
),
)
# create a list of annotation objects
annotations_list = []
for stock in stock_list:
last_value = df_stocks[stock].iloc[-1]
annotations_list.append(
dict(
# xref='x',
# x=df_stocks['date'].iloc[-1],
xref='paper',
x=1,
xanchor='left',
y=last_value,
# y=1,
yanchor='middle',
text=f'<b>{stock}</b> = ${last_value:.2f}',
showarrow=False,
font=dict(size=16, color='dimgrey'),
)
)
stock_fig.update_layout(
title_text='Investing $1 at the beginning of 2018',
title_font_color='dimgray',
title_font_family='Arial',
title_font_size=28,
title_x=0,
title_xref='paper',
paper_bgcolor='white',
plot_bgcolor='white',
showlegend=False,
annotations=annotations_list,
margin={'t': 75, 'b': 10, 'l': 10, 'r': 150},
)
# update the Y axis
stock_fig.update_yaxes(
title=None,
tickprefix='$',
tickformat='.2f',
tickfont_size=16,
tickfont_color='dimgray',
showline=False,
showgrid=True,
gridwidth=2,
gridcolor='WhiteSmoke',
# linewidth=1,
# linecolor='black',
)
# update the X axis
stock_fig.update_xaxes(
title=None,
title_font=dict(size=20, color='dimgray'),
tickfont=dict(size=16, color='dimgray'),
# tickangle=330,
# tickvals every 6 months
tickvals=['2018-01-01', '2018-07-01', '2018-12-30', '2019-07-01', '2019-12-30'],
tickformat='%b %Y',
showline=True,
linewidth=1,
linecolor='black',
)
stock_fig.update_traces(
line_width=1,
)
stock_fig['data'][-1]['line']['width'] = 3
stock_fig