df2gspread
とplotly
を
同じbokeh
を
前提
OS 、
OS
% sw_vers ProductName: Mac OS X ProductVersion: 10.12.6 BuildVersion: 16G1114
Python
% python3 -V Python 3.6.2
参考
- Pythonの
インタラクティブな 可視化ライブラリBokehで グラフを 描く - sambaiz-net - python - Plotting multiple lines with Bokeh and pandas - Stack Overflow
必要な ライブラリの インストール
df2gspread
と、bokeh
を
python3 -m pip install df2gspread --user python3 -m pip install bokeh --user
手順
以下手順を
Google Analytics から
データを エクスポート df2gspread で
データを DataFrame と して 取り込む bokeh で
可視化
Google Analytics から<wbr>データを<wbr>エクスポート
、df2gspread で<wbr> データを<wbr> DataFrame と<wbr>して<wbr>取り込む
手順は、
この
df2gspread で データを DataFrame と して 取り込む
from oauth2client.service_account import ServiceAccountCredentials def download_as_df(): from df2gspread import gspread2df as g2d # key_file 以下の指定方法だと、notebook と同じディレクトリにあるキーファイルを取得しています。 key_file = "spreadsheet_api_key.json" scope = ['https://spreadsheets.google.com/feeds'] credentials = ServiceAccountCredentials.from_json_keyfile_name(key_file, scope) # 1brCpWvk2uofc3MEt-ASb2cuZ-u8Zmx-ICxSTltlbVBQ はスプレッドシートのID なのでそれぞれ取得対象のスプレッドシートで変わります。 df = g2d.download("1cMLBDPbPkoYYX9tXIlHunAA0mt7eBEq2HaHTAxVszh4", wks_name="日次レポート", col_names=True, row_names=False, credentials=credentials, start_cell = 'A15') df = df.sort_values(by='ga:date') return df
import pandas as pd df = download_as_df() # datetime に変換する df["ga:date"] = pd.to_datetime(df["ga:date"]) # ga:date を index として設定する df.index = df["ga:date"] # グラフ描画に不要なカラムの削除 df = df.drop("ga:date", axis=1) df = df.drop("ga:avgSessionDuration", axis=1) df = df.drop("ga:pageviewsPerSession", axis=1) df = df.drop("ga:bounceRate", axis=1) # 2016-10-01 から 30日間でデータを絞り込む span = pd.date_range('2016-10-01', periods=30) df = df[df.index.isin(span)]
bokeh で 可視化
時系列グラフを
それぞれ
lineメソッドを 複数回実行する
from bokeh.plotting import figure, output_notebook, show from bokeh.models import ColumnDataSource, LabelSet output_notebook() p = figure(plot_width=800, plot_height=400, x_axis_type="datetime") # add a line renderer p.line(df.index,df["ga:users"], line_width=3,legend="ga:users", color="red") p.line(df.index,df["ga:pageviews"], line_width=3,legend="ga:pageviews",color="green") p.line(df.index,df["ga:sessions"], line_width=3,legend="ga:sessions", color="blue") # 表示 show(p)
multiline メソッドを 実行する
import pandas as pd import numpy as np from bokeh.palettes import Spectral11 from bokeh.plotting import figure, show, output_notebook output_notebook() numlines=len(df.columns) mypalette=Spectral11[0:numlines] p = figure(width=800, height=400, x_axis_type="datetime") p.multi_line(xs=[df.index.values] * numlines, ys=[df[name].values for name in df], line_color=mypalette, line_width=2) show(p)
まとめ
データラベルの
インターフェースとbokeh
のように
ぱっとplotly
の
以上です。
コメント