pandasしたい

 1import matplotlib.pyplot as plt
 2import pandas as pd
 3
 4# データを準備する
 5# x: X方向の検出位置
 6# y: Y方向の検出位置
 7# adc: 検出された値
 8data = pd.DataFrame(
 9  [
10    {"x": 1, "y": 2, "adc": 0.5},
11    {"x": 2, "y": 3, "adc": 0.7},
12    {"x": 3, "y": 1, "adc": 0.2},
13    # ... (さらにデータが続く)
14  ]
15)
16
17# レイアウトを定義する
18panels = [
19    ["profile", "hist_y"],
20    ["hist_x", "."],
21]
22
23# キャンバスを作成する
24fig, axs = plt.subplot_mosaic(
25    mosaic=panels,
26    layout="constrained",
27    figsize=(8, 6),
28)
29
30# 散布図: プロファイル
31data.plot.scatter(
32    x="x",
33    y="y",
34    c="adc",
35    ax=axs["profile"],
36    s=10,
37    cmap="viridis"
38)
39axs["profile"].set_title("Profile")
40axs["profile"].set_xlabel("X")
41axs["profile"].set_ylabel("Y")
42
43# ヒストグラム: X方向の分布
44data["x"].plot.hist(
45    ax=axs["hist_x"],
46    bins=20,
47)
48axs["hist_x"].set_title("X Distribution")
49axs["hist_x"].set_xlabel("X")
50axs["hist_x"].set_ylabel("Frequency")
51
52# ヒストグラム: Y方向の分布
53data["y"].plot.hist(
54    ax=axs["hist_y"],
55    bins=20,
56)
57axs["hist_y"].set_title("Y Distribution")
58axs["hist_y"].set_xlabel("Y")
59axs["hist_y"].set_ylabel("Frequency")
60
61# キャンバスを保存する
62fig.savefig("pandas_plot.png")

pd.DataFrame.plotで描画したグラフは、axオプションでmatplotlibのグラフと組み合わせることができます。

上のサンプルでは、 subplot_mosaicを使って、プロファイルとそれぞれの方向のヒストグラムを配置しています。

注釈

データ分析の入門書では、pd.DataFrame.plotだけで描画するサンプルを多く見かけます。 axオプションを使って、matplotlibのグラフと組み合わせることで、より柔軟にレイアウトを調整できます。