Upgrade to Pro — share decks privately, control downloads, hide ads and more …

『データ可視化学入門』を PythonからRに翻訳した話


Avatar for bob3bob3 bob3bob3
February 09, 2024

『データ可視化学入門』を PythonからRに翻訳した話


『指標・特徴量の設計から始めるデータ可視化学入門』を PythonからRに翻訳した話
です。

Avatar for bob3bob3

bob3bob3

February 09, 2024
Tweet

More Decks by bob3bob3

Other Decks in Science

Transcript

  1. 『データ可視化学入門』 『指標・特徴量の設計から始めるデータ可視化学 入門 データを洞察につなげる技術』 
 • 2023年12月発売
 • 発売前から周囲での前評判が良かったので 買ってみた。
 •

    単なるハウツー本ではなくて、「分布をどう捉 えるか」「どう指標化するか。指標化で何が 失われるか」といった分析プロセスを踏まえ た視点で書かれているのが良い。 
 • 加えて、ほとんどの可視化例について Pythonのコードが公開されているので、すぐ に試せる。

  2. どうやって翻訳したか • 文明の利器 ChatGPT を使わない手はない。
 • 実際には Copilot (旧Bing Chat)を使いました。


    • PythonのコードをCopilotに与えて「R言語で書き直してください」とお願いするだけ。
 • ただし、そのまま使えるコードが出てくることは多くない。
 • それでもかなりの工数を削減できた。

  3. ChatGPTによる翻訳例(1) import matplotlib.pyplot as plt # matplotlibのpyplotをpltとしてインポート import pandas as

    pd # pandasをpdとしてインポート import seaborn as sns # seabornをsnsとしてインポート import japanize_matplotlib # matplotlibで日本語を表示可能にする # データを辞書形式で提供 data = { 'year': list(range(1990, 2023)), # 年(1990年から2022年まで) 'population': [1.23611, 1.24101, 1.24567, 1.24938, 1.25265, 1.2557, 1.25859, 1.26157, 1.26472, 1.26667, 1.26926, 1.27316, 1.27486, 1.27694, 1.27787, 1.27768, 1.27901, 1.28033, 1.28084, 1.28032, 1.28057, 1.27834, 1.27593, 1.27414, 1.27237, 1.27095, 1.27042, 1.26919, 1.26749, 1.26555, 1.26146, 1.25502, 1.24947] # 人口(億人単位) } df = pd.DataFrame(data) # pandasデータフレームにデータを変換 plt.figure(figsize=(5, 3)) # グラフのサイズを指定 sns.lineplot(x='year', y='population', data=df, marker='o', linestyle='-') # 折れ線グラフの描画 plt.xlabel("西暦") # x軸のラベル plt.ylabel("日本の総人口 [億人]") # y軸のラベル plt.grid(True) # グリッドを表示 plt.tight_layout() # レイアウトの調整 plt.savefig("1_1_3_population_line_plot.png", dpi=300) # グラフをファイルに保存 plt.show() # グラフの表示 Pythonの原文
  4. ChatGPTによる翻訳例(1) # 必要なパッケージのインポート library(ggplot2) library(gridExtra) # データの作成 year <- seq(1990,

    2022) # 年(1990年から2022年まで) population <- c(1.23611, 1.24101, 1.24567, 1.24938, 1.25265, 1.2557, 1.25859, 1.26157, 1.26472, 1.26667, 1.26926, 1.27316, 1.27486, 1.27694, 1.27787, 1.27768, 1.27901, 1.28033, 1.28084, 1.28032, 1.28057, 1.27834, 1.27593, 1.27414, 1.27237, 1.27095, 1.27042, 1.26919, 1.26749, 1.26555, 1.26146, 1.25502, 1.24947) # 人口(億人単位) # データフレームに変換 df <- data.frame(year, population) # グラフの作成 p <- ggplot(df, aes(x=year, y=population)) + geom_line() + geom_point() + labs(x="西暦", y="日本の総人口 [億人]") + theme_bw() + theme(panel.grid.major = element_line(colour = "grey80")) # グラフの表示 print(p) 不要なgridExtraパッケージをなぜ か呼び出してる。
  5. Geminiによる翻訳例 # ライブラリの読み込み library(ggplot2) library(tidyverse) # データの準備 year <- seq(1990,

    2022) population <- c(1.23611, 1.24101, 1.24567, 1.24938, 1.25265, 1.2557, 1.25859, 1.26157, 1.26472, 1.26667, 1.26926, 1.27316, 1.27486, 1.27694, 1.27787, 1.27768, 1.27901, 1.28033, 1.28084, 1.28032, 1.28057, 1.27834, 1.27593, 1.27414, 1.27237, 1.27095, 1.27042, 1.26919, 1.26749, 1.26555, 1.26146, 1.25502, 1.24947) data <- data.frame(year = year, population = population) # 折れ線グラフの描画 ggplot(data, aes_string(x = "year", y = "population")) + geom_line(colour = "black", size = 1.2) + geom_point(colour = "red", size = 3) + labs(x = "西暦", y = "日本の総人口 [億人]") + theme_minimal() + theme(legend.position = "none") + scale_x_continuous(breaks = seq(1990, 2022, 5)) + scale_y_continuous(breaks = seq(1.24, 1.28, 0.02)) + grid(alpha = 0.5) # グラフの保存 ggsave("1_1_3_population_line_plot.png", width = 5, height = 3, dpi = 300)
  6. ChatGPTによる翻訳例(2) import seaborn as sns # グラフ作成のための Seaborn import matplotlib.pyplot

    as plt # グラフ描画のための Matplotlib import japanize_matplotlib # Matplotlibで日本語を使用可能にする from scipy import stats # 統計解析のためSciPyを読み込み plt.rcParams["font.size"] = 16 # フォントサイズの設定 penguins = sns.load_dataset("penguins") # データセットの読み込み lm = sns.lmplot(x='bill_length_mm', y='body_mass_g', hue='species', data=penguins, scatter_kws={'alpha': 0.3}, legend=False) # 回帰直線を描画 # 種ごとに回帰直線を描画 for species in penguins.species.unique(): if species is not None: # Exclude NaN species_data = penguins[penguins.species == species].dropna() # NaNを除外 slope, intercept, r_value, p_value, std_err = stats.linregress( species_data['bill_length_mm'], species_data['body_mass_g'] ) # 線形回帰分析 # 相関係数とp値の出力 print(f"For {species}:\n r value is: {r_value}\n p_value is: {p_value}") plt.xlabel('くちばしの長さ [mm]') # x軸ラベル plt.ylabel('体重 [g]') # y軸ラベル plt.show() # グラフの表示 Pythonの原文。
  7. ChatGPTによる翻訳例(2) library(ggplot2) library(palmerpenguins) # データセットの読み込み data("penguins") # 種ごとに回帰直線を描画 species_list <-

    unique(penguins$species) for (species in species_list) { if (!is.na(species)) { # Exclude NA species_data <- subset(penguins, species == species) # NAを除外 fit <- lm(body_mass_g ~ bill_length_mm, data = species_data) # 線形回帰分析 print(summary(fit)) # 相関係数とp値の出力 } } # 回帰直線を描画 ggplot(penguins, aes(x = bill_length_mm, y = body_mass_g, color = species)) + geom_point(alpha = 0.3) + geom_smooth(method = "lm", se = FALSE) + labs(x = "くちばしの長さ [mm]", y = "体重 [g]") + theme(legend.position = "none") # 凡例を削除 信頼区間はTRUEであって欲しい
  8. Gemini翻訳の一例(2) # ライブラリの読み込み library(ggplot2) library(tidyverse) library(lmtest) # データセットの読み込み penguins <-

    penguins # 回帰直線と散布図を描画 ggplot(penguins, aes_string(x = "bill_length_mm", y = "body_mass_g", color = "species")) + geom_point(alpha = 0.3) + geom_smooth(method = "lm", se = FALSE) + labs(x = "くちばしの長さ [mm]", y = "体重 [g]") + theme_minimal() # 種ごとに回帰直線と相関係数、 p値を出力 for (species in unique(penguins$species)) { if (!is.na(species)) { # NaNを除外 species_data <- penguins[penguins$species == species, !is.na(penguins[[species]])] # 線形回帰分析 lm_result <- lm(body_mass_g ~ bill_length_mm, data = species_data) # 結果の出力 print(paste0("**", species, "**")) print(paste0("相関係数:", summary(lm_result)$r.squared)) print(paste0("p値:", summary(lm_result)$coefficients[["bill_length_mm", "Pr(>|t|)"])) print() } }
  9. まとめ • 他言語からRへ翻訳するのにChatGPTはなかなか役に立つ。 ◦ そのままは使えないが下訳として使うことでだいぶ工数を減らせる。 ◦ ヒドイ翻訳例もあったがメリットの方が大きくて忘れた …… ◦ 使いたいパッケージや関数を明示すると意図したように書いてくれることが多い。

    ▪ 例えば、原文のfor文に対して「purrrパッケージのmap関数を使ってください」などと指示す る。 ◦ Copilot(旧BingChat)で十分。 ▪ ただし、Edgeは💩なのでご注意を。ポータルが最悪。 ◦ Geminiも悪くなさそう。 • Enjoy!