[EDA super basic] Plotly and dynamic visualization [python3, table, bar, box, violin, joy]

python==3.8 plotly==4.10.0

Show head

The usual

import plotly.express as px
df = px.data.tips()
df.head()

image.png

Pass the dataframe naively

import plotly.figure_factory as ff
fig = ff.create_table(df.head())#only df ok
fig.show()

image.png

Put graph objects in the figure

import plotly.graph_objects as go

fig = go.Figure(data=[go.Table(
    header=dict(values=df.columns,
                line_color='darkslategray',
                fill_color='lightskyblue',
                align='left'),
    cells=dict(values=df[0:5].transpose(),
               line_color='darkslategray',
               fill_color='lightcyan',
               align='left'))
])

fig.update_layout(width=600, height=400)
fig.show()

Of course add_trace is fine

import plotly.graph_objects as go

fig = go.Figure()
    
fig.add_trace(go.Table(
    header=dict(values=df.columns,
                line_color='darkslategray',
                fill_color='lightskyblue',
                align='left'),
    cells=dict(values=df[0:5].transpose(),
               line_color='darkslategray',
               fill_color='lightcyan',
               align='left'))
)

fig.update_layout(width=600, height=400)
fig.show()

tb.gif

bar graph

If you preprocess in advance, it will be the usual bar plot

import plotly.express as px

df_bar = df.groupby('day',as_index=False).sum()

fig = px.bar(df_bar, y='total_bill', x='day', text='total_bill')
fig.update_traces(texttemplate='%{text:.2s}', textposition='outside')
fig.update_layout(uniformtext_minsize=8, uniformtext_mode='hide')
fig.show()

image.png

If not pretreated, it will be a fine stack

import plotly.express as px

df = px.data.tips()
fig = px.bar(df, x="sex", y="total_bill", color="time",
                  title="Total Bill")
fig.update_layout(showlegend=False)
fig.show()

image.png

Use histogram instead of bar if you want to stack finely and display them all together

import plotly.express as px

df = px.data.tips()
fig = px.histogram(df, x="sex", y="total_bill", color="time",
                  title="Total Bill by Sex")
fig.update_layout(showlegend=False)
fig.show()

image.png

You can specify whether to stack (stack) or put side by side (group, dodge) in barmode.

import plotly.express as px
df = px.data.tips()
fig = px.bar(df, x="day", y="tip", color="time", barmode="group",title="bar")
fig.update_layout(font_family="Rockwell", showlegend=False)

fig.show()

image.png

Stacking by add_trace

import plotly.graph_objects as go
df = px.data.tips()
fig = go.Figure()
fig.add_trace(go.Bar(
    y=df.query("sex=='Male'")['day'],
    x=df['total_bill'],
    name='Male , total_bill',
    orientation='h',
    marker=dict(
        color='rgba(46, 78, 139, 0.6)',
        line=dict(color='rgba(46, 78, 139, 1.0)', width=3)
    )
))

fig.add_trace(go.Bar(
    y=df.query("sex=='Female'")['day'],
    x=df['total_bill'],
    name='Female , total_bill',
    orientation='h',
    marker=dict(
        color='rgba(58, 71, 80, 0.6)',
        line=dict(color='rgba(58, 71, 80, 1.0)', width=3)
    )
))

fig.update_layout(barmode='stack')

fig.show()

image.png

You can also specify animation if you have chronological (ordered) data

import plotly.express as px
df = px.data.gapminder()
fig = px.bar(df, x="continent", y="pop", color="continent",
  animation_frame="year", animation_group="country", range_y=[0,4000000000])
fig.show()

ani.gif

violin

Violin on plotly.express

import plotly.express as px
df = px.data.tips()
fig = px.violin(df, x="sex", y="tip",
                color="time", facet_col="smoker")
fig.show()

image.png

Violin in graph_objects

import plotly.graph_objects as go
df = px.data.tips()
fig = go.Figure()

for day in days:
    fig.add_trace(go.Violin(x=df['day'][df['day'] == day],
                            y=df['total_bill'][df['day'] == day],
                            name=day,
                            box_visible=True,
                            meanline_visible=True))

fig.show()

image.png

Add points and boxes

import plotly.express as px

fig = px.violin(df, x="sex", y="tip",
                color="time", facet_col="smoker",
               box=True, points="all")
fig.show()

image.png

Limited to one side on the side

from plotly.subplots import make_subplots

fig = make_subplots(rows=1, cols=2)

fig.add_trace(go.Violin(x=df.total_bill), row=1, col=1)
fig.update_traces(orientation='h', side='positive', width=3, points=False)
fig.update_layout(xaxis_showgrid=False, xaxis_zeroline=False)

fig.add_trace(go.Violin(x=df.total_bill), row=1, col=2)
fig.update_traces(orientation='h', width=3, points=False)
fig.update_layout(xaxis_showgrid=False, xaxis_zeroline=False)

fig.show()

image.png

Make one side at a time (split violin)

import plotly.graph_objects as go

fig = go.Figure()

fig.add_trace(go.Violin(x=df['day'][ df['smoker'] == 'Yes' ],
                        y=df['total_bill'][ df['smoker'] == 'Yes' ],
                        legendgroup='Yes', scalegroup='Yes', name='Yes',
                        side='negative',
                        line_color='blue')
             )
fig.add_trace(go.Violin(x=df['day'][ df['smoker'] == 'No' ],
                        y=df['total_bill'][ df['smoker'] == 'No' ],
                        legendgroup='No', scalegroup='No', name='No',
                        side='positive',
                        line_color='orange')
             )
fig.update_traces(meanline_visible=True)
fig.update_layout(violingap=0, violinmode='overlay')
fig.show()

image.png

Joy plot with violin

import plotly.graph_objects as go
from plotly.colors import n_colors
import numpy as np
np.random.seed(1)

data = (np.linspace(1, 2, 12)[:, np.newaxis] * np.random.randn(12, 200) +
            (np.arange(12) + 2 * np.random.random(12))[:, np.newaxis])

colors = n_colors('rgb(5, 200, 200)', 'rgb(200, 10, 10)', 12, colortype='rgb')

fig = go.Figure()
for data_line, color in zip(data, colors):
    fig.add_trace(go.Violin(x=data_line, line_color=color))

fig.update_traces(orientation='h', side='positive', width=3, points=False)
fig.update_layout(xaxis_showgrid=False, xaxis_zeroline=False)
fig.show()

image.png

Boxplot

Boxplot in px

import plotly.express as px
df = px.data.tips()
fig = px.box(df, x="sex", y="tip",
                color="time", facet_col="smoker")
fig.show()

image.png

Boxplot on go

import plotly.graph_objects as go
df = px.data.tips()
fig = go.Figure()

for day in days:
    fig.add_trace(go.Box(x=df['day'][df['day'] == day],
                            y=df['total_bill'][df['day'] == day],
                            name=day))

fig.show()

image.png

Add confidence intervals

You can use notched to find the confidence interval 95% of the constricted area

import plotly.express as px

fig = px.box(df, x="sex", y="tip",
                color="time", facet_col="smoker", notched=True)
fig.show()

image.png

Recommended Posts

[EDA super basic] Plotly and dynamic visualization [python3, table, bar, box, violin, joy]
[Visualization of ratio] Plotly and dynamic visualization [python, pie, sunburst, sanky, treemap, fannele,]
[Density visualization] Plotly and dynamic visualization [python3, hist, kde, join, contour, heat map]
[Drawing and labeling multiple graphs] Plotly dynamic visualization [python3, make subplot, xlabel, ylabel]
[Scatter plot, 3D plot and regression plane] Plotly dynamic visualization [python, scatter, 3D, surface, pair, joint]
[Various image analysis with plotly] Dynamic visualization with plotly [python, image]
[Time series with plotly] Dynamic visualization with plotly [python, stock price]
python memorandum super basic