Line charts#

Documentation:
https://plotly.com/python/line-charts/

Things to include:

  • line styles (e.g., dash)

  • line colors

  • legend

  • sorting the input

  • line with markers

  • date as the x axis

  • Label Lines with Annotations (this one is cool in the documentation)

  • Filled lines (this one is cool in the documentation)

  • error bars (e.g., the diff in diff example that I made)

  • shaded vertical regions (e.g., market time series with shaded recessions)

import plotly.express as px

df_stocks = px.data.stocks()
df_stocks.tail()
date GOOG AAPL AMZN FB NFLX MSFT
100 2019-12-02 1.216280 1.546914 1.425061 1.075997 1.463641 1.720717
101 2019-12-09 1.222821 1.572286 1.432660 1.038855 1.421496 1.752239
102 2019-12-16 1.224418 1.596800 1.453455 1.104094 1.604362 1.784896
103 2019-12-23 1.226504 1.656000 1.521226 1.113728 1.567170 1.802472
104 2019-12-30 1.213014 1.678000 1.503360 1.098475 1.540883 1.788185
stock_list = ['GOOG', 'AAPL', 'AMZN', 'MSFT', 'FB']

stock_fig = px.line(
	data_frame=df_stocks,
	x='date',
	y=stock_list,
	height=700,
)

# 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],
		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': 20},
)
# update the Y axis
stock_fig.update_yaxes(
	title=None,
	tickprefix='$',
	tickformat='.2f',
	tickfont_size=16,
	tickfont_color='dimgray',
	showline=True,
	linewidth=1,
	linecolor='black',
)
# update the X axis
stock_fig.update_xaxes(
	title=None,
	title_font={
		'size': 20,
		'color': 'dimgray',
	},
	tickfont={
		'size': 16,
		'color': 'dimgray',
	},
	tickangle=330,
	tickformat='%b %Y',
	showline=True,
	linewidth=1,
	linecolor='black',
)
stock_fig