LoginSignup
3
7

More than 3 years have passed since last update.

pandas Matplotlib 用途別まとめ

Last updated at Posted at 2020-06-25

項目数が多くなってきたため、Pandas に関する記述は以下に移行しました。
Pandas で○○したい - Qiita

Matplotlib

グラフ軸を設定

matplotlib.pyplot.axis — Matplotlib 3.2.1 documentation

plt.axis(xlim=(-0.005, 1.005), ylim=(0, 9000))

matplotlib.axes.Axes.set_ylim — Matplotlib 3.2.2 documentation
set_xlim()set_ylim()で軸ごとに設定することも可能。

# y軸の上限を100に設定
plt.gca().set_ylim(top=100)

ラベルの調整

ラベルの位置を指定

plt.gca().yaxis.set_label_position('right')

ラベルの座標を指定

# ラベル位置を右に指定し、座標を(x, y) = (1.25, 0.5) ずらす
# (right でのデフォルトの座標から相対的に (1.25, 0.5) ずれる挙動になる)
plt.gca().yaxis.set_label_position('right')
plt.gca().yaxis.set_label_coords(1.25, 0.5)

ラベルを非表示に

# x軸のラベルを非表示
plt.gca().set_xticklabels([])
# y軸のラベルを非表示
plt.gca().set_yticklabels([])

任意の位置に文字を配置

matplotlib.pyplot.text — Matplotlib 3.1.2 documentation

# 複数のグラフがあるときに、y軸のラベル(Response Time (s))を記入
plt.gcf().text(
  plt.gcf().axes[0].get_position().x1 - 0.45,
  plt.gcf().axes[0].get_position().y1 - 0.5,
  'Response Time (s)',
  rotation=90
)

グラフ間の幅を調整

matplotlib.pyplot.tight_layout — Matplotlib 3.1.2 documentation
【Python】 Matplotlibで出力した文字の重なりを解消する方法を紹介!│Python初心者の備忘録

plt.tight_layout()

凡例を表示

matplotlib.pyplot.legend — Matplotlib 3.1.2 documentation

plt.legend(["legend1", "legend2"])

日本語で表示

propでフォントを指定。
Matplotlibで簡単に日本語を表示する方法(Windows) | ガンマソフト株式会社

plt.legend(["二乗値"], prop={"family":"MS Gothic"})

グラフ外に表示

bbox_to_anchor で位置を指定。
python - How to put the legend out of the plot - Stack Overflow

plt.legend(["二乗値"], prop={"family":"MS Gothic"}, bbox_to_anchor=(1.05, 1))

Matplotlib で描画した散布図に直線近似した傾きを表示

# 直線近似した際の傾きを計算
a = np.polyfit(x, y, 1)[0]

ラベルの指数表記を通常表記に変更

plt.ticklabel_format(style='plain')

ラベルの数値を三桁区切りで表示

軸ラベルの数値を三桁カンマ区切りで描画する(matplotlib) - Qiita

plt.gca().xaxis.set_major_formatter(plt.FuncFormatter(lambda x, loc: '{:,}'.format(int(x))))

ラベルをソート

Legend guide — Matplotlib 3.2.2 documentation
python - How is order of items in matplotlib legend determined? - Stack Overflow

handles = []
for label in labels:
  handle = plt.scatter(..., label=label)
  handles.append(handle)

# lambda にソート基準となる関数を定義
labels, handles = zip(*sorted(zip(labels, handles)), key=lamdba x: x[0])

グラフの大きさを調整

matplotlib.pyplot.subplots_adjust — Matplotlib 3.2.2 documentation

plt.figure()

plt.subplot(121)
# ...
plt.subplot(122)
# ...

# subplot 間の幅を調整
plt.subplots_adjust(wspace=1, right=3)

ggplotを使う

ggplot はRでよく使われるグラフ化ツール。

複数レイヤーのグラフを重ねるように記述できるのが特徴?
R|ggplot2 とは|hanaori|note

plt.style.use('ggplot')

# 生存者の性別をプロット
df_train_survived = df_train_dn[df_train_dn.Survived == 1]
df_train_survived_age = df_train_survived.iloc[:, 3]
df_train_survived_male = df_train_survived.iloc[:, 2]
plt.scatter(
  df_train_survived_age,
  df_train_survived_male,
  color="#cc6699",
  alpha=0.5
)

# 死亡者の性別をプロット
df_train_dead = df_train_dn[df_train_dn.Survived == 0]
df_train_dead_age = df_train_dead.iloc[:, 3]
df_train_dead_male = df_train_dead.iloc[:, 2]
plt.scatter(
  df_train_dead_age,
  df_train_dead_male,
  color="#6699cc",
  alpha=0.5
)

plt.show()

その他

四捨五入

9.4. decimal — Decimal fixed point and floating point arithmetic — Python 2.7.18 documentation

Decimal.quantize()の第一引数で桁数を指定。

decile = lambda num: Decimal(num).quantize(Decimal('.001'), rounding=ROUND_HALF_UP)
histogram = Counter(decile(score) for score in df['Score'])
print(histogram.keys())
# dict_keys([Decimal('0.761'), Decimal('0.000'), Decimal('0.775'), ...])

map()でインデックスを使う

Getting index of item while processing a list using map in python - Stack Overflow

float 型の桁数表示を変更

Pythonのprintで桁数(数値や小数点以下など)を指定して出力する方法 | HEADBOOST

# 指数の小数点以下の桁数を三桁に指定
# e.g. float_number = 7.918330583e-06
'{:.3e}'.format(float_number)
# 7.918e-06

lambda 関数

if を使うとき

Is there a way to perform "if" in python's lambda - Stack Overflow

enumerate() を使うとき

Getting index of item while processing a list using map in python - Stack Overflow

3
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
7