【Python】Matplotlib ~ あれこれ編 ~

■ はじめに

https://dk521123.hatenablog.com/entry/2020/03/01/000000

の続き。

今回は、Matplotlib に関するTipsを纏める

目次

【1】見た目を変える
 1)インストール
 2)導入例
【2】色を変える
【3】画像ファイルとして保存
【4】注釈/矢印 でグラフを説明するには

【1】見た目を変える

可視化ライブラリ「seaborn」を使用する

https://www.sejuku.net/blog/61017
https://qiita.com/hik0107/items/3dc541158fceb3156ee0
https://qiita.com/saira/items/31328921ad0a4c203db4

1)インストール

pip install seaborn
conda install seaborn

2)導入例

import seaborn as sns

sns.set_style('darkgrid')

3)サンプル

例1:積み上げ棒グラフ
https://biotech-lab.org/articles/10875
https://pystyle.info/matplotlib-stacked-bar-chart/
https://qiita.com/s_fukuzawa/items/6f9c1a3d4c4f98ae6eb1
https://bunsekikobako.com/python_barplot_and_stack_plot_with_color_change/

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns


sns.set(font='IPAexGothic')

x = ['A', 'B', 'C']
height1 = np.array([1, 2, 1, 2, 4, 5, 3, 7, 5, 9])
height2 = np.array([1, 3, 2, 1, 2, 3, 5, 8, 6, 7])
height3 = np.array([1, 3, 3, 6, 3, 7, 4, 6, 9, 8])

fig, ax = plt.subplots()
ax.bar(x, height1)
ax.bar(x, height2, bottom=height1)
ax.bar(x, height3, bottom=height1 + height2)
plt.show()


fig, ax = plt.subplots(figsize=(10, 8))
ax.bar(dataset.columns, dataset.sum())
plt.show()

【2】色を変える

import matplotlib.pyplot as plt

cmap_names = ['hsv', 'Spectral', 'gray', 'prism']
for cmap_name in cmap_names:
  # https://qiita.com/Tatejimaru137/items/c18692d0e7144b431518  
  cm = plt.cm.get_cmap(cmap_name)
  f, ax = plt.subplots(1, 1, figsize=(10, 1))
  for idx in range(50):
    x = idx % 25
    y = -int(idx / 25)
    rgb = cm(idx / 50)
    ax.scatter(x, y, s=10**2, color=rgb)
  ax.set_title(cmap_name)

plt.show()

参考文献
https://blog.imind.jp/entry/2019/05/10/031150
https://shikaku-mafia.com/matplotlib-color/
http://hydro.iis.u-tokyo.ac.jp/~akira/page/Python/contents/plot/color/colormap.html
https://beiznotes.org/matplot-cmap-list/

【3】画像ファイルとして保存

# 画像ファイルとして保存
plt.savefig('sample_output.png')

【4】注釈/矢印 でグラフを説明するには

* plt.annotate() を使う

サンプル

# 矢印のプロパティを設定
arrow_dict = dict(
  arrowstyle="->", color="saddlebrown")

# テキストボックスのプロパティ
text_dict = dict(
  boxstyle="round", fc="silver", ec="mediumblue")
ax.annotate(
  "point A", size=14, color = "black",
  xy=(1, 1), xytext=(2, 2),
  bbox=text_dict,
  arrowprops=arrow_dict)

参考文献
https://python.atelierkobato.com/annotate/
https://qiita.com/damyarou/items/839325f73c3118f2be3b

関連記事

Matplotlib ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2020/03/01/000000
Matplotlib ~ 基本編 / 折れ線 ~
https://dk521123.hatenablog.com/entry/2023/09/17/003431
Matplotlib ~ 基本編 / 棒グラフ ~
https://dk521123.hatenablog.com/entry/2023/09/16/151516
TensorFlow ~ 環境構築 / Windows 編 ~
https://dk521123.hatenablog.com/entry/2018/02/17/102927
scikit-learn ~ 機械学習用ライブラリ・基本編 ~
https://dk521123.hatenablog.com/entry/2020/03/08/113356
NumPy ~ 数値計算ライブラリ ~
https://dk521123.hatenablog.com/entry/2018/03/28/224532
Pandas ~ データ解析支援ライブラリ ~
https://dk521123.hatenablog.com/entry/2019/10/22/014957