seaborn
必要ライブラリーのimport
以下で行う。今回は必要最小限のみ。
import pandas as pd
import numpy as np
from matplotlib import pylab as plt
import seaborn as sns
sns.set()
plt.style.use("seaborn-whitegrid")
用いるデータセット
Tipsデータセットを用いる。
tips = sns.load_dataset("tips")
調整方法
例えばbarplotで行ってみる。
sns.barplot(data = tips, y = "total_bill", x = "day", hue = "sex")
とするとなんの変哲もない以下の図が出力される。

例えば、このx軸の金曜日のラベルのみ赤色にしたいとする。ここで結構ハマって時間を潰したので、今回記事に。
具体的方法
きちんとmatplotlibの構造を意識していれば簡単だった。
g = sns.barplot(data = tips, y = "total_bill", x = "day", hue = "sex")
と、まずgraphplotを引数として渡す。この引数からはaxes情報が引き出せるので、それらを設定してやるといい。
g.axes.get_xticklabels()[1].set_color("r")

解説
matplotlibを階層構造で理解すると良い。Figure > axes > axis > artistと階層になっており 順に深い階層と考える。

FigureオブジェクトやAXesオブジェクトを作成する最も簡単な方法は以下のコードである。
fig = plt.figure() # axesの無い空のfigure
fig, ax_lst = plt.subplots(2, 2) # 2x2 gridのAxesを持つfigure
figureは美術館、axexは絵のキャンバス、axisが額縁で、artistが絵そのものと考えると良い。解剖図は以下の様になる。

例えば、上のTipsのグラフで、xlabelを”day”から”weekday”に、fontsizeを16に変更したい時はこのようにすれば良い。
g.axes.set_xlabel("weekday", fontsize=16)
この階層構造が理解できていれば、後は関数の適応だけなので、いじりたい部分を自由にいじることが出来る。

lagendのタイトルを変更する
この場合も上と同様に、
lg = g.fig.legends[0]
lg.set_title("Change legend title")
としてあげれば良い。
コメント