# Python 互動式圖表筆記(1) ploty
###### tags: `plotly` `Python`
為了整理過往的資料視覺化報告,並架設一個互動式資料呈現的網站,開了這個相關筆記本,此篇先做一些網路範例
## 基本的ploty
```python=
from plotly.offline import iplot
import plotly.figure_factory as ff
import pandas as pd
```
用pandas讀入資料並用ploty的crate_table呈現
```python=
df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/school_earnings.csv")
table =ff.create_table(df)
iplot(table,filename="jupyter-table1")
```
![](https://i.imgur.com/IJuYCZZ.png)
用ploty畫柱狀圖(bar圖)
```python=
import plotly.graph_objects as go
schools = df.School
data=[go.Bar(x=df.School,y=df.Gap)]
iplot(data, filename ='jupyter-basic_bar')
```
![](https://i.imgur.com/7KXHcf3.png)
挑戰看看3D圖
我們用iris的資料,並用PCA降維成3維
```python=
from sklearn.datasets import load_iris
from sklearn.decomposition import PCA
iris = load_iris()
X= iris.data
y_label=iris.target
pca=PCA(n_components=3)
X_pca=pca.fit_transform(X)
```
檢查一下資料
```python=
display(X[:5],
y_label[:5],
X_pca[:5])
```
定義要呈現的
```python=
plot_df = pd.DataFrame(X_pca)
```
嘗試用Scatter3d繪製
(ploty的3d圖有許多不同的類別可選擇,可上官網查詢使用方法)
https://plotly.com/python/3d-charts/
```python
trace_data = []
fig= go.Figure(data=[go.Scatter3d(
x=plot_df[0],
y=plot_df[1],
z=plot_df[2],
mode ='markers',
marker=dict(size=12,
color = y_label,
colorscale='Viridis',
opacity=0.8))]
)
```
最後show出3D圖
```python
fig.update_layout(margin=dict(l=0,r=0,b=0,t=0))
fig.show()
```
![](https://i.imgur.com/rkiGzIW.png)
## 兩張圖表
```python=
import plotly.express as px
from plotly.subplots import make_subplots
import plotly.graph_objects as go
import plotly.io as pio
pio.renderers.default='browser'# 讓展示的方式是用browser
fig = make_subplots(specs=[[{"secondary_y": True}]])
## 設定要用到第二個y
fig.add_trace(
go.Scatter(x=train_data['Date'],y=train_data['CDA_A'], name="CDA MVT"),
secondary_y=False,
)
## 第一個y secondary_y用False
fig.add_trace(
go.Scatter(x=train_data2['Date'],y=train_data2['CDA_IGV'], name="CDA IGV"),
secondary_y=True,
)
## 第二個y secondary_y用TRUE
### Add figure title
fig.update_layout(
title_text="Relationship between IGV and MVT"
)
### Set x-axis title
fig.update_xaxes(title_text="Date")
### Set y-axes titles
fig.update_yaxes(title_text="<b>CDA MVT</b>", secondary_y=False)
fig.update_yaxes(title_text="<b>CDA IGV</b>", secondary_y=True)
fig.show()
```
## 關於X軸或Y軸的 limit
```python
fig.update_scenes(xaxis_range=(200,300))
fig.update_scenes(yaxis_range=(0,60))
```
## Scala 類型
```python
import plotly.express as px
fig = px.scatter(newdata, x="All_max", y="All_std", color="health_check",
size='health_check', hover_data=['health_check'])
pyo.plot(fig, filename = 'plot.html')
```
## 顏色選擇
CSS color:
aliceblue, antiquewhite, aqua, aquamarine, azure,
beige, bisque, black, blanchedalmond, blue,
blueviolet, brown, burlywood, cadetblue,
chartreuse, chocolate, coral, cornflowerblue,
cornsilk, crimson, cyan, darkblue, darkcyan,
darkgoldenrod, darkgray, darkgrey, darkgreen,
darkkhaki, darkmagenta, darkolivegreen, darkorange,
darkorchid, darkred, darksalmon, darkseagreen,
darkslateblue, darkslategray, darkslategrey,
darkturquoise, darkviolet, deeppink, deepskyblue,
dimgray, dimgrey, dodgerblue, firebrick,
floralwhite, forestgreen, fuchsia, gainsboro,
ghostwhite, gold, goldenrod, gray, grey, green,
greenyellow, honeydew, hotpink, indianred, indigo,
ivory, khaki, lavender, lavenderblush, lawngreen,
lemonchiffon, lightblue, lightcoral, lightcyan,
lightgoldenrodyellow, lightgray, lightgrey,
lightgreen, lightpink, lightsalmon, lightseagreen,
lightskyblue, lightslategray, lightslategrey,
lightsteelblue, lightyellow, lime, limegreen,
linen, magenta, maroon, mediumaquamarine,
mediumblue, mediumorchid, mediumpurple,
mediumseagreen, mediumslateblue, mediumspringgreen,
mediumturquoise, mediumvioletred, midnightblue,
mintcream, mistyrose, moccasin, navajowhite, navy,
oldlace, olive, olivedrab, orange, orangered,
orchid, palegoldenrod, palegreen, paleturquoise,
palevioletred, papayawhip, peachpuff, peru, pink,
plum, powderblue, purple, red, rosybrown,
royalblue, rebeccapurple, saddlebrown, salmon,
sandybrown, seagreen, seashell, sienna, silver,
skyblue, slateblue, slategray, slategrey, snow,
springgreen, steelblue, tan, teal, thistle, tomato,
turquoise, violet, wheat, white, whitesmoke,
yellow, yellowgreen
## 在jupyter notebook 中顯示
要先init
```python=
# Import the necessaries libraries
import plotly.offline as pyo
import plotly.graph_objs as go
# Set notebook mode to work in offline
pyo.init_notebook_mode()
```
## 參考資料:
https://medium.com/datainpoint/interactive-gapminder-with-python-90f8d604a0a2
https://medium.com/ichitsai/vis-plot-ly-offline-python-%E8%B3%87%E6%96%99%E8%A6%96%E8%A6%BA%E5%8C%96-f4b540c130f8
https://ithelp.ithome.com.tw/articles/10214872
https://plotly.com/python/plotly-fundamentals/
#### 3D
https://plotly.com/python/3d-charts/
#### 兩個以上的y
https://plotly.com/python/multiple-axes/
### 顏色處理
https://plotly.com/python/builtin-colorscales/