Plotly

March 31, 2023

Sane plotly defaults, margins, with legends inside chart

import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
plotly_config = dict(
    autosize=True,
    margin=dict(l=0, r=0, b=0, t=0, pad=0),
)
fig.update_layout(**plotly_config)
fig.update_layout(legend=dict(
    yanchor="top",
    y=0.99,
    xanchor="center",
    x=0.1,
))
_filename = 'filename'
fig.write_image(f'{_filename}.svg')
fig.show()

Setting plotly labels

fig = px.bar(df['url'].resample('1w').count(), labels={'value': 'Disruptions'}).update_layout(
    autosize=True,
    margin=dict(l=0, r=0, b=0, t=0, pad=0),
).update_layout(showlegend=False)
fig.write_image("image.svg")
fig.show()

Pivot operations and MultiIndex to flat columns

important = russia_bans
important.loc[~russia_bans['product'].str.startswith(_cols), 'product'] = 'Other'

sanctions_with_other = (important
    .groupby(
        by=[important['date.implemented'], important['product'].str[:2]],
        group_keys=True,
    )
    .count()
    .rename(columns={'product': 'product.count'})
    .reset_index('product')
    .loc[:, ['product', 'product.count']]
)
sanctions_with_other = pd.DataFrame(
    sanctions_with_other.pivot(columns=['product'])
)
sanctions_with_other.columns = sanctions_with_other.columns.get_level_values(1)
# Only for including "Other"
sanctions_with_other = sanctions_with_other.loc[:, ('Ot',) + _cols].rename(columns={'Ot': 'Other'})
sanctions_with_other.index = pd.to_datetime(sanctions_with_other.index)

Helper: Embedding plotly charts as static images for (PDF) export

EXPORT_TO_PDF = False

import os
from IPython.display import Image
def plotly_img_save_and_inline(fig, filename):
    fig.write_image(f'{filename}.svg')
    fig.write_image(f'{filename}.png', width=1000)
    if EXPORT_TO_PDF:
        print('To pdf, saving')
        img = Image(data=f'{filename}.png', width=1000)
        # Declutter by removing the png file from disk again,
        # we only need vector graphics
        os.remove(f'{filename}.png')
        return img
    print('Inline')
    fig.show()

fig = px.line(
    strikes.resample('d').count()
)
_filename = 'image'
plotly_img_save_and_inline(fig, _filename)