Life is Like a Boat

忘備録や経済、投資、プログラミングに関するメモやtipsなど

Google AnalyticsをPlotly Dashで作ったサイトに追加する

Dashで作成したページにGoogle Analyticsを埋め込む方法です。

  1. Google Analyticsのサイトから新規にアカウントを作成。トラッキングIDが生成される。 f:id:nerimplo:20180919121814p:plain

  2. Plotly Dashの/assetsディレクトリ下にgtag.jsを作成する。

  3. ソースは下記の通り。

(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

ga('create', 'YOUR_TRACKING_ID', 'auto');
ga('send', 'pageview');

なんとこれだけです。

/assetsディレクトリ下にはカスタムのcssやJavascriptを置く事ができます。これらはDash側から特段指定せずに自動的にロードされます。

Including custom CSS or JavaScript in your Dash apps is simple. Just create a folder named assets in the root of your app directory and include your CSS and JavaScript files in that folder. Dash will automatically serve all of the files that are included in this folder.

dash.plot.ly

なお、dashが他のコマンドラインから走る場合(flaskコマンドやgunicornなど)、mainモジュールはapp.pyがある場所にはないので、app = dash.Dash(name)とセットしてあげる必要があります。