BigQuery DataFrames を使用してグラフを可視化する

このドキュメントでは、BigQuery DataFrames 可視化ライブラリを使用してさまざまな種類のグラフをプロットする方法について説明します。

bigframes.pandas API は、Python 用のツールの完全なエコシステムを提供します。この API は高度な統計オペレーションをサポートし、BigQuery DataFrames から生成された集計を可視化できます。また、組み込みのサンプリング オペレーションを使用して、BigQuery DataFrames から pandas DataFrame に切り替えることもできます。

ヒストグラム

次の例では、bigquery-public-data.ml_datasets.penguins テーブルからデータを読み取り、ペンギンのくちばしの深さの分布に関するヒストグラムをプロットします。

import bigframes.pandas as bpd

penguins = bpd.read_gbq("bigquery-public-data.ml_datasets.penguins")
penguins["culmen_depth_mm"].plot.hist(bins=40)

BigQuery DataFrames のヒストグラムの例。

折れ線グラフ

次の例では、bigquery-public-data.noaa_gsod.gsod2021 テーブルのデータを使用して、年間の中央値の気温変化の折れ線グラフをプロットします。

import bigframes.pandas as bpd

noaa_surface = bpd.read_gbq("bigquery-public-data.noaa_gsod.gsod2021")

# Calculate median temperature for each day
noaa_surface_median_temps = noaa_surface[["date", "temp"]].groupby("date").median()

noaa_surface_median_temps.plot.line()

BigQuery DataFrames の折れ線グラフの例。

面グラフ

次の例では、bigquery-public-data.usa_names.usa_1910_2013 テーブルを使用して、米国史における名前の人気を追跡し、MaryEmilyLisa という名前に焦点を当てています。

import bigframes.pandas as bpd

usa_names = bpd.read_gbq("bigquery-public-data.usa_names.usa_1910_2013")

# Count the occurences of the target names each year. The result is a dataframe with a multi-index.
name_counts = (
    usa_names[usa_names["name"].isin(("Mary", "Emily", "Lisa"))]
    .groupby(("year", "name"))["number"]
    .sum()
)

# Flatten the index of the dataframe so that the counts for each name has their own columns.
name_counts = name_counts.unstack(level=1).fillna(0)

name_counts.plot.area(stacked=False, alpha=0.5)

BigQuery DataFrames の面グラフの例。

棒グラフ

次の例では、bigquery-public-data.ml_datasets.penguins テーブルを使用してペンギンの性別の分布を可視化します。

import bigframes.pandas as bpd

penguins = bpd.read_gbq("bigquery-public-data.ml_datasets.penguins")

penguin_count_by_sex = (
    penguins[penguins["sex"].isin(("MALE", "FEMALE"))]
    .groupby("sex")["species"]
    .count()
)
penguin_count_by_sex.plot.bar()

BigQuery DataFrames の棒グラフの例。

散布図

次の例では、bigquery-public-data.new_york_taxi_trips.tlc_yellow_trips_2021 テーブルを使用して、タクシー料金と乗車距離の関係を調べます。

import bigframes.pandas as bpd

taxi_trips = bpd.read_gbq(
    "bigquery-public-data.new_york_taxi_trips.tlc_yellow_trips_2021"
).dropna()

# Data Cleaning
taxi_trips = taxi_trips[
    taxi_trips["trip_distance"].between(0, 10, inclusive="right")
]
taxi_trips = taxi_trips[taxi_trips["fare_amount"].between(0, 50, inclusive="right")]

# If you are using partial ordering mode, you will also need to assign an order to your dataset.
# Otherwise, the next line can be skipped.
taxi_trips = taxi_trips.sort_values("pickup_datetime")

taxi_trips.plot.scatter(x="trip_distance", y="fare_amount", alpha=0.5)

BigQuery DataFrames の散布図の例。

大規模なデータセットを可視化する

BigQuery DataFrames は、可視化のためにデータをローカルマシンにダウンロードします。ダウンロードするデータポイントの数は、デフォルトで 1,000 個に制限されています。データポイントの数が上限を超えると、BigQuery DataFrames は上限と同じ数のデータポイントをランダムにサンプリングします。

次の例に示すように、グラフをプロットするときに sampling_n パラメータを設定することで、この上限をオーバーライドできます。

import bigframes.pandas as bpd

noaa_surface = bpd.read_gbq("bigquery-public-data.noaa_gsod.gsod2021")

# Calculate median temperature for each day
noaa_surface_median_temps = noaa_surface[["date", "temp"]].groupby("date").median()

noaa_surface_median_temps.plot.line(sampling_n=40)

BigQuery DataFrames で大規模なデータセットを可視化する折れ線グラフの例。

pandas と Matplotlib のパラメータを使用した高度なプロット

BigQuery DataFrames のプロット ライブラリは pandas と Matplotlib を基盤としているため、pandas と同様に、グラフを微調整するためのパラメータを渡すことができます。以降のセクションでは、例について説明します。

サブプロットを使用した名前の人気度の傾向

面グラフの例の名前履歴データを使用して、次の例では、plot.area() 関数呼び出しで subplots=True を設定して、名前ごとに個別のグラフを作成します。

import bigframes.pandas as bpd

usa_names = bpd.read_gbq("bigquery-public-data.usa_names.usa_1910_2013")

# Count the occurences of the target names each year. The result is a dataframe with a multi-index.
name_counts = (
    usa_names[usa_names["name"].isin(("Mary", "Emily", "Lisa"))]
    .groupby(("year", "name"))["number"]
    .sum()
)

# Flatten the index of the dataframe so that the counts for each name has their own columns.
name_counts = name_counts.unstack(level=1).fillna(0)

name_counts.plot.area(subplots=True, alpha=0.5)

BigQuery DataFrames のサブプロットを含む個々のグラフの例。

複数のディメンションを含むタクシー乗車数の散布図

散布図の例のデータを使用して、次の例では、x 軸と y 軸のラベルの名前を変更し、点のサイズに passenger_count パラメータを使用し、tip_amount パラメータで色付きの点を使用し、図のサイズを変更します。

import bigframes.pandas as bpd

taxi_trips = bpd.read_gbq(
    "bigquery-public-data.new_york_taxi_trips.tlc_yellow_trips_2021"
).dropna()

# Data Cleaning
taxi_trips = taxi_trips[
    taxi_trips["trip_distance"].between(0, 10, inclusive="right")
]
taxi_trips = taxi_trips[taxi_trips["fare_amount"].between(0, 50, inclusive="right")]

# If you are using partial ordering mode, you also need to assign an order to your dataset.
# Otherwise, the next line can be skipped.
taxi_trips = taxi_trips.sort_values("pickup_datetime")

taxi_trips["passenger_count_scaled"] = taxi_trips["passenger_count"] * 30

taxi_trips.plot.scatter(
    x="trip_distance",
    xlabel="trip distance (miles)",
    y="fare_amount",
    ylabel="fare amount (usd)",
    alpha=0.5,
    s="passenger_count_scaled",
    label="passenger_count",
    c="tip_amount",
    cmap="jet",
    colorbar=True,
    legend=True,
    figsize=(15, 7),
    sampling_n=1000,
)

BigQuery DataFrames で複数のディメンションを含む散布図の例。

次のステップ