Plotly vs Seaborn

Libraries

  • Both Seaborn and Plotly are nice charting libs in python

  • This comparison is my personal subjective view and reminder to myself of the nice features of each.

import pandas as pd
import numpy as np
import seaborn as sns
sns.set_theme()
import seaborn.objects as so
import plotly.express as px
import matplotlib.pyplot as plt

Datasets

Load a few popular datasets to use

penguins = sns.load_dataset("penguins")
healthexp = sns.load_dataset("healthexp")
gapminder = px.data.gapminder()
iris = sns.load_dataset("iris")
iris.columns = [col.replace('_', ' ') for col in iris.columns]

Line chart

  • Plotly need to summarize the data before plotting
  • Seaborn has built-in stats function and distribution allows plot a distribution in charts

Here is a plotly chart.

fig = px.line(gapminder.groupby(["continent","year"]).mean("leftExp").reset_index(),
              x="year", 
              y="lifeExp", 
              color="continent", 
              line_group="continent", 
            #   line_group="country", 
            #   hover_name="country",
              line_shape="spline", 
              render_mode="svg",
              # width=600,
              template="seaborn"
              )
fig.show()

Here is a plotly chart.

Here is the seaborn chart.

A lot less code needed, and more features in the chart.

fig = sns.lineplot(gapminder, 
              x="year", 
              y="lifeExp", 
              hue="continent")
plt.show()

Bar chart

Seaborn bar plot

automatically shows a clustered bar with built-in stats for average and error bar, but creating a stacked bar seems difficult.

sns.barplot(penguins, x="species", y="body_mass_g", hue="sex")
plt.show()

Seaborn bar plot

Plotly

It needs to manually compute stats and no error bar. but otherwise shows a clusters bar easily

px.bar(
    (penguins
     .groupby(["species", "sex"])
     .mean("boday_mass_g")
     .reset_index()),
    x="species",
    y="body_mass_g",
    color="sex",
    barmode="group",
    width=700,
    template="seaborn"
)

Plotly

Pair plot

Seaborn

Built-in stats make the a lot better than plotly

fig = sns.pairplot(
    iris,
    hue="species",
    height=1.5,
    # corner = True,
    )
fig.map_upper(sns.kdeplot) 
plt.show()

Seaborn

Plotly

scatter matrix is scatter only.

fig = px.scatter_matrix(
    iris,
    dimensions=["sepal length", "sepal width", "petal length", "petal width"],
    color="species",
    template="seaborn",
    title="Title",
    # labels={col:col.replace('_', ' ') for col in df.columns},
    height = 600
    )
    # .update_traces(diagonal_visible=False)
fig.show()

Plotly

Plotly features

We already see the interactive nature. It also has nice type of charts like sunburst and geo plots

A sunburst chart

It shows hierarchy and hover info is very useful here.

df = px.data.gapminder().query("year == 2007")
fig = px.sunburst(df, path=['continent', 'country'], values='pop',
                  color='lifeExp', 
                  hover_data=['iso_alpha'],
                  color_continuous_scale='rdbu',
                  color_continuous_midpoint=np.average(df['lifeExp'], 
                  weights=df['pop']),
                  # width=500
                  )
fig.show()

A sunburst chart

A geo plot

Use iso_alpha codes and plot population.

fig = px.scatter_geo(df, locations="iso_alpha",
                     size="pop",
                     color='pop',
                     # size of markers, "pop" is one of the columns of gapminder
                    #  width=500
                     )
fig.show()

A geo plot

Line Geo

Plot routes in the earth surface

fig = px.line_geo(df.iloc[:2,], locations="iso_alpha",
                  color="year", # "continent" is one of the columns of gapminder
                #   projection="orthographic",
                  projection="natural earth",
                  # width=500
                  )
fig.show()

Line Geo

Animation

Here is the gapminder animation using plotly.

fig = px.scatter(gapminder, x="gdpPercap", y="lifeExp", animation_frame="year", animation_group="country",
           size="pop", color="continent", hover_name="country", 
        #    facet_col="continent",
           log_x=True, size_max=45, range_x=[100,100000], range_y=[25,90])
fig.show()

Animation