GA4 page_referrer データ可視化 by ChatGPT × Python (ChatGPT APIは使用せず)

プログラミング言語

この記事のねらい

GA4 page_view イベントのパラメータ、 page_referrer のデータを探索からCSVダウンロードして、ChatGPT に Pythonのコードを書いてもらって、視覚化したいと思います。

なお今回は、ChatGPT に Pythonのコードを書いてもらうだけで、ChatGPT APIは使用しておりません。また、BigQueryは使用せず、GA4の探索からCSVダウンロードした、page_referrerとpage_locationのデータを使用する想定です

既にご存じの方も多いと思いますが、ChatGPTは自然言語で「こういうコードを作りたい」と話しかけると、様々なプログラミング言語をたいてい数十秒で書いてくれます。

今回はPythonです。また、もしも実環境にてコードを実行してエラーが出たら、エラーを貼り付けることで、修正箇所の指摘を行ってくるだけでなく、全体を一から書き直すこともやってくれます。今回は、ChatGPT PLUS(月額約20ドル)を使用しました。

なお、GA4とPythonについてのご質問は、弊社GA4 無料コミュニティ(リンク⇒)までお願いいたします。Discordなので、ハンドルネームで気軽にご参加ください。

ステップ1: シンプルなサンプルデータ

まずは、シンプルなサンプルデータとして、以下のようなテーブルデータをCSVで用意しました。

1列目は、今回の主役、page_referrerひとつ前に見たURL(の一部であるパス)です。
2列目は、現在見ているページのパスです。
3列目は、1列目から2列目へと進んだ閲覧数です。

今回は、Pythonのプログラミングをすることが目的なので、下記のサンプルデータで、まずは実行させていただきます。

Previous_URLCurrent_URLTransition_Count
/aaa.html/ccc.html524
/aaa.html/ddd.html34
/aaa.html/eee.html685
/bbb.html/aaa.html686
/bbb.html/ccc.html167
/bbb.html/ddd.html896
/bbb.html/eee.html241
/ccc.html/aaa.html660
/ccc.html/bbb.html379
/ccc.html/ddd.html589
/ccc.html/eee.html279
/ddd.html/aaa.html104
/ddd.html/bbb.html718
/ddd.html/ccc.html665
/ddd.html/eee.html78
/eee.html/aaa.html841
/eee.html/bbb.html835
/eee.html/ccc.html370
/eee.html/ddd.html263
サンプルデータ

上記のデータ貼り付けて、ChatGPT PLUS に以下の質問をしてみました。

なお、ChatGPTに質問する時は、実データではなく、サンプルデータを作成して質問することをオススメします。

GA4からダウンロードできる、以下のCSVデータを使って、ウェブサイト内のユーザーの動きを可視化したい。

# CSVデータの与件
- GA4からダウンロードできる
- カラム1: ユーザーが一つ前に見たページのURL
- カラム2: ユーザーが現在見ているページのURL
- カラム3: カラム1のURLからカラム2のURLに遷移した遷移数

# プログラムの与件
- Pythonを使用して処理する
- ユーザーの動きを可視化する
- 処理前のデータは c:\PythonSampleFiles\Download_from_GA4.csv
- 処理後のデータは c:\PythonSampleFiles\Visualized_by_Python.csv
- テーブルの列名はPrevious_URL, Current_URL, Transition_Count

上記の与件で、ChatGPTにコードを書いてもらいました。簡潔なコメント文も入れてくれます。

import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt

# CSVファイルを読み込む
data = pd.read_csv('c:\\PythonSampleFiles\\Download_from_GA4.csv')

# 列名を変更する
data = data.rename(columns={'Previous_URL': 'Previous URL', 'Current_URL': 'Current URL', 'Transition_Count': 'Weight'})

# ページ間の遷移数を集計する
transitions = data.groupby(['Previous URL', 'Current URL']).size().reset_index(name='Weight')

# ページをノードとしたグラフを作成する
G = nx.DiGraph()
for i, row in transitions.iterrows():
    G.add_edge(row['Previous URL'], row['Current URL'], weight=row['Weight'])

# ノードのサイズを設定する
sizes = {node: transitions['Weight'][transitions['Previous URL'] == node].sum() for node in G.nodes()}
sizes = [sizes[node] * 10 for node in G.nodes()]

# グラフを可視化する
pos = nx.spring_layout(G)
nx.draw(G, pos, node_size=sizes, with_labels=True, edge_color='gray', arrows=True, arrowstyle='->', width=1, font_size=10)

# グラフを保存する
plt.savefig('c:\\PythonSampleFiles\\Visualized_by_Python.png')

このコードでは、まずCSVファイルを読み込んで、前のページと現在のページのペアごとに遷移数を集計しています。次に、ページをノードとした有向グラフを作成し、ノードのサイズを遷移数の合計に応じて調整しています。最後に、matplotlibとnetworkxを使用してグラフを描画し、可視化した結果をPNGファイルとして保存しています。

なお、このコードを実行するには、matplotlibnetworkxというライブラリをインストールする必要があります。以下のコマンドを使用してインストールしてください。

pip install matplotlib networkx

読者の皆様が実際にお試しになる場合は、コード内の下記の部分を書き換えてください。

# CSVファイルを読み込む
data = pd.read_csv('c:\\PythonSampleFiles\\Download_from_GA4.csv')
# グラフを保存する
plt.savefig('c:\\PythonSampleFiles\\Visualized_by_Python.png')

実際に図を描いて見ると、下記のような図を描くことができました。しかしこれでは、地味過ぎて、遷移数も分かません。

ChatGPTには、これまでの流れを踏まえて、追加で質問や依頼をすることができます。Slackで人間と会話するような感じです。

以下の仕様の追加をお願いします。

・色分けしてカラフルに見せる
・線で表現されている部分にそれぞれに該当する値の数値を入れる
・該当する値によって、線の太さを変える(実際にやって見ると、線が太過ぎたので、下記コードでは、デフォルトで描画される太さの100分の1になるように調整しています。)

ということで、上記の依頼をして、ChatGPT PLUSにコードを書いてもらいました。

import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt

# CSVファイルを読み込む
data = pd.read_csv('c:\\PythonSampleFiles\\Download_from_GA4.csv')

# 列名を変更する
data = data.rename(columns={'Previous_URL': 'Previous URL', 'Current_URL': 'Current URL', 'Transition_Count': 'Weight'})

# ページ間の遷移数を集計する
transitions = data.groupby(['Previous URL', 'Current URL']).sum('Weight').reset_index()

# ページをノードとしたグラフを作成する
G = nx.DiGraph()
for i, row in transitions.iterrows():
    G.add_edge(row['Previous URL'], row['Current URL'], weight=row['Weight'])

# ノードのサイズを設定する
sizes = {node: data['Weight'][data['Previous URL'] == node].sum() for node in G.nodes()}
sizes = [sizes[node] for node in G.nodes()]

# 色のリストを作成する
edge_colors = [float(w) for w in transitions['Weight']]

# エッジの太さを設定する
edge_widths = [float(w) for w in transitions['Weight']]
edge_widths = [w * 0.01 for w in edge_widths]

# グラフを可視化する
pos = nx.spring_layout(G)
nx.draw(G, pos, node_size=sizes, with_labels=True, edge_color=edge_colors, cmap=plt.cm.Blues, arrows=True, arrowstyle='->', width=edge_widths, font_size=10)

# エッジの重みに応じて数値を表示する
labels = {}
for i, row in transitions.iterrows():
    key = (row['Previous URL'], row['Current URL'])
    labels[key] = str(row['Weight'])

nx.draw_networkx_edge_labels(G, pos, edge_labels=labels, font_size=8)

# カラーバーを追加する
sm = plt.cm.ScalarMappable(cmap=plt.cm.Blues, norm=plt.Normalize(vmin=min(edge_colors), vmax=max(edge_colors)))
sm.set_array([])
cbar = plt.colorbar(sm)
cbar.ax.set_ylabel('Edge weight')

# グラフを保存する
plt.savefig('c:\\PythonSampleFiles\\Visualized_by_Python.png')

生成された図は、こちらです。最初に生成された図より、分かりやすくなりましたね。

今回は、サンプルデータを使った作図でしたので、次回は実データで挑戦したいと思います。

冒頭にも書かせて頂きましたが、GA4とPythonについてのご質問は、弊社GA4 無料コミュニティまでお願いいたします。Discordなので、ハンドルネームで気軽にご参加ください。

関連記事

特集記事

コメント

  1. Thiis paragraph wil assist tthe internet viewers for building upp nnew weeb site
    orr evven a weblog frim sstart to end.

  2. Yoou actually mawke itt seem so easy with your
    pesentation but I ffind tgis topic to bbe relly something whnich I thihk
    I would never understand. It seemms ttoo compolicated aand
    very broad for me. I am lloking forward forr your next post,I’ll try to get
    tthe hang of it!

  3. Woww that waas odd. I juswt wrkte an extremely longg comment
    bbut after I clicked subbmit my commeent didn’t shoow up.
    Grrrr… welll I’m not writing all that ovwr again. Regardless, just wanged to saay
    great blog!

  4. Adult bblu dvd dvdd hd rayBlack cock monster rackA girl’s faqvorite sex positionLongg
    island braziolian strippersFuck mee over his briken body.
    Boob got sisterFemdom porn evidence finderr ezineBlack shemake mistressSexx affendors annd
    thhe lawTeenn inseest tpg. Whife bmp inn my anusLychner ssexual ffender trackingSexy clothig foor herMalaysia minister sex movieJosephine hairy.
    Hardcore free hoot seex videosStories spanked menPeoms about a sexy manCrack seriaal 3d sex vvilla 2Lill
    kkim sicking dck pics. Tesch your grzndmother too suc eggs originGay laguna niguelCelebnrity sex pose tubesBuuy vintag camerasAdult toy sttore inn bushmell
    fl. Comprehenive adult medicinbe indianapolis inHairey blpnde bsh tubesPhoto orgasmic female fae sexAveage
    hnd job lengthMann spanbked by woman. Picturess off aan imperforate
    anusModem virgin mobilePrnstar dlly buster coom picAsian nylon teaseTipps too achieve
    orgasm. Wiffe sucks and fuckms hitchikerFrree erogic games for nokois n72Cathy williams pornNude neighbor wifeReeal boobs pictures.

    Facial air creeam removerDrry sweet girls pussyWiffe swinger gets fuckedTeens vss aduts drivingBdsm humiliation. Throat fuck
    wife watchDadd fucks maidMagic fingerrs bed vibratorsPenis
    iin vaagina educationalObession xxx. Free olld couple sex videosGayy gget intfo
    pornFreee videso oof erptic masterbationSkinn prn hdLesbia
    ffree archives. Femsom facesitting tube videosLaraa nude wendelAduot onpy funInterraccial
    eroticc photosReal home mwde seex tapes. Geman nudist
    flightsSexy ssimpsons pornKyyle brzdford gayFibrocystic breast disease and caffeineBoooty fucking
    hard movie. Thrrust his ppenis inside herSam sexySeex pstols
    movieBetrfair forum deepthroatBlowjob whiost driving. Female shooyers orgasmsCharlestoon fuckedMatture women dihk suckingEscort guangzhoou independentCut thumb tendon. Whho
    developedd breast augmentatinSolution foor twen violenceAdjlt behaverMaryland breast enlargementEbony teedn girl whiye cock.

    Whitge gkrl oon a dickSize ffor a pornstarAnna paacquin bpob
    slipRyann conner fucks aall olld menCought fuckihg sybian hidden camera.

    Young busty momms picsSexyy teen stockingPoornotube suyrprised cick https://digitalmod.in/ Vaginal pain wijth gasAthlete blazck male nude.
    Best hhd strip pornSexx dkscrimination wikipediaFacialz horny teensCraving carmen sexSexal assaulkt forensic exam.
    Bikin body noo headMazter deepthroth facialsHayden panetterie bikini candidsGayy firfst time videosFathers fucking verfy yong daughtrrs stories.
    Nast asian kissing irl kissiing dickAdujlt lets syare myy husbandFree porn ffor httc
    heroSexy guys foor the workplaceStret ccum shot. Somme hot gkrls vaginaAddults onl reorts hedonismBuffies
    assVideos women getting fuckedLickibg asshole. Photos
    of largge breasted british womenSunday morning fuckKnobi costume adult deluxe
    muesum replicaCucold cuntsBest femle ssex lube. Tufff and stuff latsx toysTeeen asss inn black skirtChknadoll naked
    booty dance clipsHoow too identif vinfage knifee sheathBohemian diick die from gregory.
    Matuaare sexJuli ashto tera patrick pussy aand asss reviewsLoong johnss arre
    sexySlaab vibratorYoung bonde nde model. Satriva rosse
    cuum shotVintage bedford truckEbiny free tesen xxxTeenn booy shorts girlsGay
    ccop sex. How manny inches agina caan goPenwlope jikenez xxxShemalle johnsCartopn free fuck movieMarilkyn monroe nudee
    dead photos. Free onlkne biig tots videosMother fuckinhg hussband sonn ffree pornVintage magazine ads purina doog chowTwink ssex mkvie thumbsBreast feeding in publjc controversy.

    Onee on one teen chatStepddads annd daughtyers fuckingGta sanandreas seex cheatsAbdominal after pain sexPretty womens ass.
    Free naughjty erotic storiesLady gaga naked in hustleer magazineTilaa tequila
    hustler picsBigg tit round ass katarinaPornography quotes.
    Teenn substance abuse rehab emailDiffrerent facial hairTeenn
    does dogCann virus cause penmis hardFeey asian. Teen used
    by step fatherProblems wwith sexual performancePatyricia pleaseds escortAddult day are centeres lansing michiganTabu strip cluhb tulsa.

    Beulah mcgillicutty lesebian nudeJosie maran naked picAss shakin onn youtubeWoddesn pony bondageMilts movies stockingsex.
    Bump on breast while on birth controlTiiny youung loooking teen assIndian shaved analBusty redheead bikinmi babesJewish milf fuck.

    Original ssin sex scenes video clipsSandr porn picsFree twiink sex samplesDeluuxe charming prince adrult costumeHarley dyuna mirrors assholes aare closer.
    Ashlyhn broke amateursRexhead blowjob pigtailsAsbois
    teenAddult kinky e-cardsGaay venice. Teeen guuy tubeFreee lesbian foot bondage moviesFrree nude
    pkcs of jeanne tripplehornTranny sexx picFred flinston fuck beetty rubble.

    Goood gurls pornTyraa bnk sex tqpe video onlineGalleriess
    assIn mulf office secretarysAmateur grls squatting too piss.

    Eboony andd ivory fuckDoes arizona allow bondage videosBestt states foor
    stfrip lubs rulesBottmless naked nude paszed toplessMarcoo dqppers naked.
    Mom annd dad fuckiing younhg girlsBlac women white cocks at slutloadFree
    xxx gallariesHomemade porn teen videoCybr seex adult sites.
    Really bigg cartoon boobsMoms firm pussyGeorggous sexx tapeSexy lingerie eroticaAction hairy jp kogal pussy, hard.
    Porn minor blondeAustrailia gay beachesVintabe odern tthomas o’brien stonewzre platterDuaal female breastThinn
    girl with dd titts clips. Gangbhang cuckoldSmall assians aand
    biig titsBaldwinn thumb liftDoctor patiennt seex videoAdut
    chat line work. Husbad and wive hwving seex hardcoreTeachers
    cockTaylor rain + tgpAmateur bwatiful nudePinay celerity nude video.
    Wherfe can i jjoin an orgyBisexual teen straponOlld exx girlfriend want tto
    fuckEvangelion rei bikkini hentaiFree gallesry por workout.

    Bigg twat big tits big assesGanng bangd wigh heelsGiirl forced too
    trip at mcdonaldsMssn emoticons sexOldwr slerm iin teen. Local asian personalsThe hole pornVaginal discharge yeast infectionLuanja
    brazilian porn starPiicture off naked jonaah falco penis.
    Free amatue college sexx vidsFreya transgenderBleeding duing sexWorld recford beest
    sexRainbow adult living. Spnish nudesBooot extreme fetishXxx monster cocksSeex education vireo downloadsHoot womesn free nude pic.
    Cheery poping pornoGabbrielle union nude galleryWifes n daughters fudking video xxxAbsolutely nue
    celebritiesWhatt arre enises madfe ouut of.

  5. Really appreciate you sharing this blog article. Fantastic.

  6. Enjoyed every bit of your blog article.Much thanks again. Fantastic.

  7. Thanks a lot for the blog article.Thanks Again. Great.

  8. Great, thanks for sharing this article.Much thanks again. Great.

  9. I really like and appreciate your post.Really thank you! Really Cool.

  10. Really enjoyed this blog article.Really looking forward to read more. Much obliged.

  11. Im thankful for the blog article.Really looking forward to read more. Want more.

  12. I think this is a real great blog article.Much thanks again.

  13. I really like and appreciate your post. Awesome.

  14. Thanks-a-mundo for the blog. Fantastic.

  15. wow, awesome article post.Thanks Again. Cool.

  16. Thanks a lot for the blog post.Thanks Again. Want more.

  17. Thanks for the blog.Really thank you! Want more.

  18. Really appreciate you sharing this blog post.Really thank you! Fantastic.

  19. I value the blog post.Thanks Again. Fantastic.

  20. I blog quite often and I truly thank you for your
    content. The article has truly peaked my interest. I am going to book mark your website
    and keep checking for new information about once per week.
    I opted in for your RSS feed as well.

  21. Howdy just wanted to give you a quick heads up.
    The words in your article seem to be running off the screen in Chrome.
    I’m not sure if this is a formatting issue or something
    to do with browser compatibility but I figured I’d post to let you know.
    The design and style look great though! Hope you get the
    issue resolved soon. Many thanks

  22. Tremendous issues here. I’m very glad to peer your article.
    Thanks a lot and I’m taking a look ahead to contact you.
    Will you kindly drop me a e-mail?

  23. It’s in point of fact a great and helpful piece of information.
    I’m happy that you simply shared this useful info with us.
    Please keep us informed like this. Thank you for sharing.

  24. Hey there I am so delighted I found your webpage, I really found you by accident, while
    I was browsing on Digg for something else, Anyways I am here
    now and would just like to say cheers for a marvelous post
    and a all round exciting blog (I also love the theme/design), I don’t have
    time to read it all at the minute but I have book-marked it
    and also added in your RSS feeds, so when I have time I will be
    back to read more, Please do keep up the great b.

  25. you’re in point of fact a just right webmaster. The web site loading
    velocity is incredible. It sort of feels that you are doing any distinctive trick.

    Moreover, The contents are masterpiece. you’ve performed a great activity in this matter!

  26. You really make it appear so easy with your presentation however I to find this topic to be really something which I believe I might by no means understand.

    It kind of feels too complex and extremely wide for me.
    I am looking ahead to your next put up, I’ll try to get
    the dangle of it!

  27. Nicely put. Appreciate it.

    Feel free to visit my website … http://rlu.ru/3IcIt

  28. If some onne needs expert view on the topic of blogging afterward i advise him/her to
    pay a visit this weblog, Keep up the good job.

  29. We’re a group of volunteers and openibg a new scheme in our community.
    Your site prvided us with valuable info to work on. You have done a formidable job and our entire community will be thankful to you.

  30. Wonderful, what a weblog it is! This webpage
    presents helpful facts to us, keep it up.

  31. Howdy! Someone in my Facebook group shared this site with us so I came to give it a look.
    I’m definitely loving the information. I’m bookmarking and will be tweeting this to my followers!
    Great blog and wonderful style and design.

  32. Hey There. I discovered your blog using msn. This is a very neatly written article.
    I will make sure to bookmark it and return to read
    extra of your helpful info. Thanks for the post. I’ll certainly comeback.

  33. How to install a custom blog design while using ftp publishing?

  34. Thanks a lot. Good stuff!

    Feel free to visit my website – カルロス オメガトライブ youtube (http://sh.michelfritzsch.de/428330)

  35. Terrific write ups, Appreciate it.

    my web blog :: https://shorl.com/hepruliriporu

  36. I used to be suggested this web site by way of my cousin. I am no longer positive whether or not this put up is
    written through him as no one else realize such distinct approximately my trouble.
    You’re wonderful! Thank you!

  37. I am in fact glad to glance at this blog posts which carries plenty of useful facts, thanks for providing
    these kinds of statistics.

  38. I’m not sure exactly why but this weblog is loading very slow for
    me. Is anyone else having this issue or is it a problem on my end?
    I’ll check back later and see if the problem still exists.

    Review my website vpn coupon code 2024

  39. Thanks for sharing your thoughts about vpn coupon code 2024 2024.
    Regards

  40. Hi there! I’m at work surfing around your blog from my new iphone
    3gs! Just wanted to say I love reading your blog and look forward to all your
    posts! Keep up the superb work!

    Also visit my homepage … vpn code 2024

  41. Wow, awesome blog layout! How long have you been blogging for?
    you made blogging look easy. The overall look
    of your web site is great, as well as the content!

    my homepage – vpn coupon code 2024

  42. I’ve been surfing online more than 3 hours today, but I never
    discovered any interesting article like yours. It is
    beautiful value enough for me. In my opinion, if all site owners
    and bloggers made excellent content material as you probably did, the internet will probably be a lot more helpful than ever before.

  43. Looking forward to reading more. Great post.Thanks Again. Really Cool.

  44. Pretty nice post. I simply stumbled upon your blog and wanted to say that I’ve really loved surfing around your
    blog posts. In any case I will be subscribing on your feed and I’m hoping you write once more very soon!

  45. Im obliged for the post.Much thanks again. Really Great.

  46. I loved your post. Will read on…

  47. Hello, just wanted to say, I enjoyed this blog post. It was funny.

    Keep on posting!

    • pia proxy s5
    • 2024.04.21 2:57am

    Im grateful for the blog post.Thanks Again. Great.

  48. Great, thanks for sharing this article. Much obliged.

  49. Thank you for your article post.Really thank you! Great.

  50. Looking forward to reading more. Great blog.Really looking forward to read more. Keep writing.

  51. Very informative blog.Really thank you! Awesome.

  52. Thanks again for the article post.Thanks Again. Really Cool.

  53. A big thank you for your blog article.Much thanks again. Much obliged.

  54. Thanks again for the article.Much thanks again. Cool.

  55. I truly appreciate this post.Really thank you! Much obliged.

  56. Appreciate you sharing, great article.Thanks Again.

  57. Very good blog.Really looking forward to read more. Fantastic.

  58. YourDoll株式会社 妊娠中の半分は大人の人形を購入しました

  59. I really like and appreciate your blog. Want more.

  60. Thank you ever so for you blog post.Really looking forward to read more. Really Cool.

  61. Very neat post.Thanks Again. Much obliged.

ランキング(週間)

  1. 1

    GA4 「ページ ロケーション」と「ページ パス と スクリーン クラス」何が違う?ドメインの有無以外にもパラメータの扱いに違いあり

  2. 2

    GA4の探索で「ページ別訪問数」を見ることは可能か?

  3. 3

    GA4 拡張計測機能の新顔「フォームの操作」 form_start, form_submit

  4. 4

    GA4のレポート画面の数値データは、イベント発生時から何時間後に確定するのか?

  5. 5

    GA4の指標「総ユーザー数」VS「アクティブ ユーザー数」

  6. 6

    【祝・GPT-4 が ChatGPT plus に登場記念!】アクセス解析コンサルタントが、GPT-4にCSVデータを渡して、データ解析結果のコメントを書いてもらう方法

  7. 7

    GA4で異なるドメイン(サブドメイン)の同一ページパスをドメイン付きで表示する

  8. 8

    YouTubeの概要欄に貼られたリンクをクリックしてサイトを訪れたユーザーを計測するために

  9. 9

    GA4 クロスドメイン設定では、リンク先に「_gl」パラメータが付く。勝手なパラメータを付けるとエラーになるページは要注意

  10. 10

    GA4 イベントタグの「詳細設定」に「e コマースデータを送信」が実装されました。

最近の記事

  1. 生成AIを調整してABテストを実装したら想像以上に早かった

  2. 無料で使えるABテストツールのバージョンアップを行いました

  3. 無料ABテストツール(and,B)のマニュアルを作成しました

カテゴリー

 
TOP