はじめに
完全に僕のためのmatplotlibまとめです。いつかちゃんと読みやすい記事にしようと思います
こちらの拡張版みたいなものです。
役に立つサイト
- matplotlibでジャーナルに投稿可能な図を作るためのメモ – Qiita
- [Python] matplotlib: 論文用に図の体裁を整える – Qiita
- 早く知っておきたかったmatplotlibの基礎知識、あるいは見た目の調整が捗るArtistの話
小技集
上付き文字などLaTeX表記したいとき
plt.rcParams['mathtext.default'] = 'default'
plt.rcParams['mathtext.fontset'] = 'stix'
#例
molname = ['$H_2O$',"$CO_2$","$CH_4$","$CO$","$N_2O$","$NO$","$O_3$","$HCl$"]
横に凡例を並べる(例えば4つ要素があるとき)
plt.legend(fontsize = 16,loc='upper right',ncol=4)
logスケールのグラフの数値を整数で表す
plt.gca().xaxis.set_major_formatter(matplotlib.ticker.ScalarFormatter())
plt.gca().xaxis.set_minor_formatter(matplotlib.ticker.ScalarFormatter())
x軸を上下にそれぞれとる
fig = plt.figure()
ax1 = fig.subplots()
ax2 = ax1.twinx()
ax1.plot(...)
ax2.plot(...)
画像のように2個の凡例を一つにまとめたいとき
from matplotlib.legend_handler import HandlerLine2D, HandlerTuple
df = pd.read_excel("test.xlsx")
p1 = plt.scatter(df.iloc[:,2],df.iloc[:,3],c="white",linewidths="1",edgecolors="r")
p2 = plt.scatter(df.iloc[:,0],df.iloc[:,1],c="white",linewidths="1",edgecolors="b")
p3, = plt.plot(df.iloc[:,2],df.iloc[:,5],color="r")
p4, = plt.plot(df.iloc[:,0],df.iloc[:,4],color="b")
plt.legend([(p1, p3),(p2, p4)], ['test1','test2'], numpoints=1,
handler_map={tuple: HandlerTuple(ndivide=None)})
凡例の枠線をなくしたいとき
plt.legend(frameon=False)
ある文字列からある文字列までデータをスライスする
#コラム名指定
collmun = ["c0","c1"]
df = pd.read_csv("5.0w.csv",names = collmun)
#ある文字列からある文字列までのindexを得る
start = df.index[df["c0"] == "[Data]"].tolist()[0]
end = df.index[df["c0"] == "[EndOfFile]"].tolist()[0]
#上記で得た配列にスライス
x,y = df.iloc[start+1:end,0].tolist(),df.iloc[start+1:end,1].tolist()
#文字列のデータを数字列に変換
x,y = [float(i) for i in x],[float(i) for i in y]
コメント