公開・実測日:2026年11月22日。
どのコードを変えるとこの結果になりますか?
この図では、第1群はx=1–5、応答12–16、第2群はx=6–10、応答1–5です。群内で直線を当て、全体の1本の最小二乗線と比べます。
本記事では説明用のシミュレーションデータを使います。


実際の出力はどう変わりますか?
全体の傾きは約-1.42424で、各群は+1です。修正後は群の所属と群内の線を示しますが、10観測は変えません。
| x | response | group |
|---|---|---|
| 1 | 12 | A |
| 2 | 13 | A |
| 3 | 14 | A |
| 4 | 15 | A |
| 5 | 16 | A |
| 6 | 1 | B |
| 7 | 2 | B |
| 8 | 3 | B |
| 9 | 4 | B |
| 10 | 5 | B |
表は入力の全行です。 (10)
この設定を使う前に何を確認しますか?
群別と全体の相関は異なる階層の関連を示します。研究上の問いに合う階層を選び、研究デザインと合わせて解釈します。
図を再現してファイルを取得するには?
書き込み可能なフォルダーで python example.py を実行します。実行環境は Python 3.12.4、Matplotlib 3.8.4、NumPy 1.26.4です。スクリプトと同じ場所に data.csv、before.png、after.png、after.pdf を作ります。
以下は本文で使ったコード、データ、実行結果のファイルです。コードを動かしたり、自分の結果と見比べたりするときに使ってください。
- example.py自分のパソコンで実行できる例のコード一式です。
- data.csv例に使った入力データです。表として開けます。
- before.png比較用の変更前の図です。
- after.png本文の設定で作成した結果の図です。
- after.pdf閲覧やページへの配置に使える PDF 形式の結果です。
- 利用条件 · LICENSE.txtコード・データ・図の利用条件と、出典・フォントの情報。
ファイルの確認
- hashes.jsonダウンロードしたファイルの完全性を確認するための照合値です。
完全な Python コード
# Original Bopbun code/data: CC0-1.0. Font rights remain separate; see LICENSE.txt.
# Tested: Python 3.12.4, Matplotlib 3.8.4, NumPy 1.26.4.
from pathlib import Path
import csv
import json
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib import colors, ticker, dates
OUT=Path(__file__).resolve().parent
plt.rcdefaults()
plt.rcParams.update({'font.family':'DejaVu Sans','font.size':11,'figure.dpi':120,
'savefig.dpi':160,'pdf.fonttype':42})
def data_file(header,rows):
with (OUT/'data.csv').open('w',newline='',encoding='utf-8') as f:
w=csv.writer(f);w.writerow(header);w.writerows(rows)
def canvas(**kw):
return plt.subplots(figsize=(7.2,4.5),layout='constrained',**kw)
def make(fixed):
x=np.arange(1,11);y=np.r_[np.arange(12,17),np.arange(1,6)];group=np.array(['A']*5+['B']*5);data_file(['x','response','group'],zip(x,y,group));fig,ax=canvas()
if fixed:
for g in ['A','B']:
mask=group==g;ax.scatter(x[mask],y[mask],label=g);ax.plot(x[mask],np.polyval(np.polyfit(x[mask],y[mask],1),x[mask]))
ax.legend(title='Group')
else:ax.scatter(x,y);ax.plot(x,np.polyval(np.polyfit(x,y,1),x),label='Pooled fit');ax.legend()
ax.set(xlabel='x',ylabel='Response (a.u.)',title='Within-group and pooled slopes answer different questions');return fig
if __name__=='__main__':
before=make(False);after=make(True)
before.savefig(OUT/'before.png');after.savefig(OUT/'after.png')
after.savefig(OUT/'after.pdf',metadata={'CreationDate':None,'ModDate':None})
after.canvas.draw()
print(json.dumps({'axes':len(after.axes),'limits':[{'x':list(a.get_xlim()),'y':list(a.get_ylim())} for a in after.axes]}))
plt.close('all')
参照元と商用利用の条件は何ですか?
独自のコードとデータは CC0-1.0です。図は DejaVu Sans を使い、フォントの許諾は別途保持します。Matplotlib と NumPy はインストール済みの依存関係を呼び出し、配布しません。
R言語入門

