【EDA超基礎】plotlyで動的な可視化をする【python3,table,bar,box,violin,joy】

python==3.8
plotly==4.10.0


#headを表示

いつもの

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


![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/275572/32c16330-8316-eb4e-0816-851da75ac7e8.png)


##素朴にdataframeを渡す


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




![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/275572/0aeb650b-f3b4-91f5-02f0-50508c57c91e.png)






##Figure にgraph objectsを入れる


```python
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()
```

もちろんadd_traceでもいい


```python
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](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/275572/4c3e4fd6-117c-d1c3-3e71-368c822b1f95.gif)


#棒グラフ

##事前に前処理をしておけばいつものbar plotになる


```python
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](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/275572/29da588c-ce2f-435c-d30b-4a6e7415f9fb.png)


##前処理していないと細かい積み上げになる

```python
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](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/275572/37bc28b1-5e5c-3ef8-c209-e91ae60388d3.png)




##細かい積み上げ、まとめて表示したければbarでなくhistgramを使う


```python
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](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/275572/fb220049-6adc-9503-eb74-920b52b23dd5.png)



##barmodeで積み上げ(stack)かグループで横に置くか(group,dodge)を指定することができる


```python
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](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/275572/8daeb95d-2442-cd9b-f441-dc99c06a5122.png)




##add_traceによる積み上げ



```python
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](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/275572/f896b5cd-9455-73e0-0fc6-057532acd645.png)


##年代(順序のある)データがついていればanimationを指定することもできる

```python
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](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/275572/70d2a5e5-1c7e-99fa-9bbd-9121fb628708.gif)




#バイオリン


##plotly.expressでバイオリン


```python
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](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/275572/91fb2df3-291b-7573-446c-ccd127813f7b.png)


##graph_objectsでのバイオリン

```python
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](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/275572/693e9cba-6691-412c-da18-1e2b9009c67b.png)






##点と箱を追加する

```python
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](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/275572/90d14001-8d78-2567-8bad-4bafcdcddf9e.png)




##sideで片面に限定する


```python
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](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/275572/0a702864-01bc-3580-864c-a8d87ffaf037.png)





##片面ずつ作って合わせる(split violin)


```python
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](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/275572/496c30c6-b20e-0e86-b45d-e3cf370ed3e7.png)

##バイオリンを使ったjoy plot


```python
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](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/275572/2a7d09ea-d456-9344-3a6d-a6a4eeb802be.png)



#箱ひげ


##pxでの箱ひげ


```python
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](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/275572/6e762a8a-bbb2-ca2b-641b-499203e504ce.png)




##goでの箱ひげ

```python
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](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/275572/5c4125a9-ceac-8e47-9b85-40c6c95712c8.png)


##信頼区間を付ける
notchedを使うと信頼区間を調べられる
くびれている範囲が95%区間


```python
import plotly.express as px

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






![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/275572/260784c3-08dd-83bd-d6bd-da093c6e4d54.png)