
- Plotly教程
- Plotly - 首頁
- Plotly - 簡介
- Plotly - 環境搭建
- Plotly - 線上和離線繪圖
- 在Jupyter Notebook中內聯繪圖
- Plotly - 包結構
- Plotly - 匯出為靜態影像
- Plotly - 圖例
- Plotly - 格式化座標軸和刻度
- Plotly - 子圖和內嵌圖
- Plotly - 條形圖和餅圖
- Plotly - 散點圖、Scattergl圖和氣泡圖
- Plotly - 點圖和表格
- Plotly - 直方圖
- Plotly - 箱線圖、小提琴圖和等高線圖
- Plotly - 分佈圖、密度圖和誤差條形圖
- Plotly - 熱力圖
- Plotly - 極座標圖和雷達圖
- Plotly - OHLC圖、瀑布圖和漏斗圖
- Plotly - 3D散點圖和曲面圖
- Plotly - 新增按鈕/下拉選單
- Plotly - 滑塊控制元件
- Plotly - FigureWidget 類
- Plotly結合Pandas和Cufflinks
- Plotly結合Matplotlib和Chart Studio
- Plotly有用資源
- Plotly - 快速指南
- Plotly - 有用資源
- Plotly - 討論
Plotly結合Pandas和Cufflinks
Pandas是Python中非常流行的資料分析庫。它也擁有自己的繪圖函式支援。但是,Pandas繪圖不提供可互動的視覺化效果。值得慶幸的是,可以使用**Pandas DataFrame**物件構建Plotly的互動式和動態繪圖。
我們首先從簡單的列表物件構建DataFrame。
data = [['Ravi',21,67],['Kiran',24,61],['Anita',18,46],['Smita',20,78],['Sunil',17,90]] df = pd.DataFrame(data,columns = ['name','age','marks'],dtype = float)
DataFrame的列用作圖形物件軌跡的**x**和**y**屬性的資料值。在這裡,我們將使用**name**和**marks**列生成條形軌跡。
trace = go.Bar(x = df.name, y = df.marks) fig = go.Figure(data = [trace]) iplot(fig)
一個簡單的條形圖將如下所示在Jupyter Notebook中顯示:

Plotly建立在**d3.js**之上,它是一個專門的圖表庫,可以使用另一個名為**Cufflinks**的庫直接與**Pandas DataFrame**一起使用。
如果尚未安裝,請使用您喜歡的包管理器(如**pip**)安裝Cufflinks包,如下所示:
pip install cufflinks or conda install -c conda-forge cufflinks-py
首先,匯入Cufflinks以及其他庫,例如**Pandas**和**numpy**,這些庫可以將其配置為離線使用。
import cufflinks as cf cf.go_offline()
現在,您可以直接使用**Pandas DataFrame**顯示各種型別的繪圖,而無需像之前那樣使用**graph_objs模組**中的軌跡和圖形物件。
df.iplot(kind = 'bar', x = 'name', y = 'marks')
條形圖,與之前的非常相似,將如下所示:

來自資料庫的Pandas DataFrame
除了使用Python列表來構建DataFrame之外,還可以使用不同型別資料庫中的資料填充它。例如,可以將來自CSV檔案、SQLite資料庫表或MySQL資料庫表的資料提取到Pandas DataFrame中,最終使用**Figure物件**或**Cufflinks介面**將其用於Plotly圖形。
要從**CSV檔案**獲取資料,我們可以使用Pandas庫中的**read_csv()**函式。
import pandas as pd df = pd.read_csv('sample-data.csv')
如果資料位於**SQLite資料庫表**中,則可以使用**SQLAlchemy庫**按如下方式檢索:
import pandas as pd from sqlalchemy import create_engine disk_engine = create_engine('sqlite:///mydb.db') df = pd.read_sql_query('SELECT name,age,marks', disk_engine)
另一方面,從**MySQL資料庫**檢索資料到Pandas DataFrame的方式如下:
import pymysql import pandas as pd conn = pymysql.connect(host = "localhost", user = "root", passwd = "xxxx", db = "mydb") cursor = conn.cursor() cursor.execute('select name,age,marks') rows = cursor.fetchall() df = pd.DataFrame( [[ij for ij in i] for i in rows] ) df.rename(columns = {0: 'Name', 1: 'age', 2: 'marks'}, inplace = True)