12
9

More than 1 year has passed since last update.

matplotlib in julia:PyPlotメモ

Last updated at Posted at 2015-10-02

juliaでPyPlot(matplotlib)を使った作図をするとき,細かな調整方法についての記載が少ない.
以下,デフォ設定+困った際になんとかしたメモ(随時更新).
どうしようも無い時でもPyCallからのpyimportで大抵はなんとかなるはず.

'22.08.04: 内容がJuliaとPyPlotのだいぶ古いversion用だったので修正・追記

参考URL:
https://gist.github.com/gizmaa/7214002
http://docs.juliaplots.org/latest/examples/pyplot/
https://gist.github.com/gizmaa/7214002#basicplots
http://nanyakan.blogspot.jp/2013/03/matplotlib.html
http://www.turbare.net/transl/scipy-lecture-notes/intro/matplotlib/matplotlib.html

ファイルに出力
savefig("./dat.pdf", transparent="True",bbox_inches="tight", pad_inches=0.1)

最初に定義

default値の変更: http://matplotlib.org/1.3.1/users/customizing.html

using PyCall
using PyPlot

#defaultのフォントを設定
fs=9
rc("font",family ="Arial",size=fs) 
rc("font",serif ="Arial",size=fs) 

## PyPlot.matplotlib.rc
# rc("text",usetex ="true") #TeXでのフォントが普通のになる
# rc("text.latex",preamble ="\\usepackage{amsmath}") # L"aa, $x_2$" みたいな感じで混ぜて書ける
rc("mathtext",fontset="custom") # mathjax使ったほうが楽,  L"eq., $2 b^2$

#defaultのfigureサイズを設定
cm=1/2.54
rc("figure",figsize =([8.6,6]cm), )
rc("lines",markersize = 4)
rc("lines",linewidth = 0.5)
rc("lines",markeredgewidth = 1.0)
rc("xtick",top="on",direction="in")
rc("ytick",right="on",direction="in")
rc("legend", frameon=0)
         
#デフォルトの色のセットを変更
col=("#D50000","#2962FF","#2E7D32","#FF6D00",
     "#9A12B3","#795548","#FF80AB","#26C6DA",
     "#64DD17","#AEA8D3","#616161","black")

@pyimport cycler as cyc
rc("axes",prop_cycle=cyc.cycler(color=col) )

色の巡回リセット

gca().set_prop_cycle(color=col)

色セット

https://flatuicolors.com/
http://www.flatuicolorpicker.com/

# seaborn style
@pyimport seaborn as sns

sns.set_style({"lines.markeredgewidth"=> 0.5,})
sns.set_style("white")
sns.set_style("ticks", {"xtick.major.size"=> 8, "ytick.major.size"=> 8})
sns.set_style({"xtick.direction" => "in", "ytick.direction"=> "in",
    "font.family"=> {"Times New Roman"},
    "font.sans-serif"=> {"Times New Roman"}})

図のサイズ

figure(figsize=(4,3),)

図の比率を固定

gca().set_aspect("equal", adjustable="box")

図のスケール

axis("scaled") # 横軸と縦軸のスケールを揃える
axis("image")
xscale("log") # log-scale
yscale("log")

ax=gca()
# major ticksの間隔が空いた場合
locmaj = matplotlib.ticker.LogLocator(base=10,numticks=12) 
ax.xaxis.set_major_locator(locmaj)

# minor ticksが消えた場合
locmin=matplotlib.ticker.LogLocator(base=10.0,subs=(0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9),numticks=12)
ax.xaxis.set_minor_locator(locmin)
ax.xaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())

axhline(0, color="k") # 横
axvline(0, color="k") # 縦

手書き風

rc("text",usetex ="false")
xkcd()

プロットのオプション

plot(datx, daty , "ro-", 
	mec="none", mew=1, mfc="pink", mew=1,markersize=6,
	label="r=$r1_1 A")

ヒストグラム

PyPlot.plt.hist(x[:],500,alpha=0.6)

他のプロット:ベクトル場,

ベクトル場

quiver(x,z, datx, datz, datz, color="tomato", pivot="mid",angles="xy",scale_units="xy",scale=0.8,)
clim(-1,1) # color のrange

凡例

legend(loc="best",title=L"L\, \rm(nm)",frameon=0, ncol=1, labelspacing=0.5,
columnspacing=-0.5, numpoints=1, markerscale=1, handlelength=1.5,)
#		bbox_to_anchor=(0.83, 0.24), handletextpad=0.5)

# labelの順序を逆に
handles, labels = gca().get_legend_handles_labels()
legend(reverse(handles), reverse(labels) )

# フレームの太さを変えたい
al=legend(title="なにか記述")
al.get_frame().set_linewidth(0.5)   # :set_edgecolor("k") で色も変えられる。

# 凡例を複数に分割して記述する

line11, =plot(x1,y1, label="Type I")
line12, =plot(x2,y2, label=L"(21,7,5)")

leg1=legend(handles=[line11,line12], loc="upper right")
gca().add_artist(leg1)

line21, =plot(x3,y3, label="Type II")
line22, =plot(x4,y4, label=L"(7,7,15")

leg2=legend(handles=[line11,line12], loc="center right")


# labelを空白にする
# labelには適当に文字を入れておく
# プロットデータとlabelの情報取得
handles, labels = gca().get_legend_handles_labels() 
## 該当箇所のラベルを文字なしにする
labels[1:3].=""
## プロットする
legend(handles,labels, title=L"L_x~\rm(nm)",loc="best",frameon=0, ncol=2, labelspacing=0.4,
columnspacing=-0.5, numpoints=1, markerscale=1, handlelength=1.,fontsize=9,)

###色 color map
http://matplotlib.org/users/colormaps.html

cmap=get_cmap("Paired",10)
co(i)=pycall(cmap,PyAny,i)

# co(数字)で色を指定
x=(1:10)
for i=1:20
    n=i/30.0
    plot(x,x.^n,"o-",color=co(n),mfc="w",mec=co(n),mew=1.5)
end

###テキスト

annotate( L"text", xy=(0.55,0.44), xycoords="axes fraction", bbox=Dict(:boxstyle=>"round",:ec=>"none", :fc=>"gray", :alpha=>0.2),)

# xyはグラフの範囲内にしておかないといけない、xytextで位置調整が出来る
annotate("Ferro",xy=[-7,-556.9], xytext=[-7,-556.99]) 

Tex記法

ylabel(L"\displaystyle \frac{1}{2}") # \displaystyle で分数表記がバランス良くなる

# using LaTeXStrings

# PyDict(pyimport("matplotlib")["rcParams"])["text.usetex"] = [true]
# PyDict(pyimport("matplotlib")["rcParams"])["text.latex.preamble"] = ["\\usepackage{amsmath}"]
#  -> 
rc("text",usetex ="true")
rc("text.latex",preamble ="\\usepackage{amsmath}")


###矢印
http://matplotlib.org/examples/pylab_examples/annotation_demo2.html

arrow(x0,y0, vecx, vecy, lw=0.5,length_includes_head=true, head_width=3, head_length=0.5, fc="k", ec="k")

annotate(L"text_c",
xy=[0.5,0.20], xytext=[0.2,0.05], xycoords="data", textcoords="data",size=10,
arrowprops=Dict("arrowstyle"=>"-|>","fc"=>"k","ec"=>"k", "connectionstyle"=>"arc3,rad=0.1") )

annotate(L"text_c",
xy=[0.5,0.06], xytext=[0.9,0.09], xycoords="data", textcoords="data",size=10,
arrowprops=Dict("arrowstyle"=>"-|>","fc"=>"k","ec"=>"k", "connectionstyle"=>"angle,angleA=0,angleB=90,rad=10",))

Error bar

errorbar(x,y, yerr=e,capsize=1.5,elinewidth=0.5, fmt=".-", color=c_cycle[ic] )
plot(x,y,"m.-", label=L"-0.5")

色々定義

    xform  = gca().xaxis.set_major_formatter
    xmform = gca().xaxis.set_minor_formatter
    yform  = gca().yaxis.set_major_formatter
    ymform = gca().yaxis.set_minor_formatter
    
    xloc  = gca().xaxis.set_major_locator
    xmloc = gca().xaxis.set_minor_locator
    yloc  = gca().yaxis.set_major_locator
    ymloc = gca().yaxis.set_minor_locator
    
    ftick = matplotlib.ticker.FormatStrFormatter
    stick = matplotlib.ticker.ScalarFormatter
    ltick = matplotlib.ticker.MultipleLocator

上記の定義のもとでのフォーマットの変更

# 軸の数字表記
yform(ftick("%1.1f"))

#軸の肩に指数をつける, scilimitsで指数の範囲を指定
yform(stick(useMathText=true))
gca().ticklabel_format(style="sci",axis="y",scilimits=(0,0)) 
gca().yaxis.offsetText.set_fontsize(14)
    
#50ごとにsubticksをつける
gca().xaxis.set_minor_locator(ltick(50))

枠を消す

gca().spines["right"].set_color("none")
gca().spines["top"].set_color("none")

ticksの変更色々

ax.tick_params(axis="y", direction="in", pad=1) # pad で軸との隙間を決める.

subplot:複数図

subplot(4,3,1)
    subplots_adjust(hspace=0.2,wspace=0.1)    
    xticks((2:2:16),())
    
    
# 縦に4分割 2:1:1
#sub1
subplot2grid((4,1), (0,0),  rowspan=2)

#sub2
#subplot2grid((6,2), (0,1), rowspan=2) 
subplot2grid((4,1), (2,0),  colspan=1)

#sub3
subplot2grid((4,1), (3,0),  colspan=1)

目盛り

tick_params(axis="x",top="on" , labeltop="on",direction="in",length=6.5, width=3.5,which="major",color="r",labelcolor="g")
rc("xtick",top="on", color="black")

# 左右で異なる軸
twinx()

# x軸の数字のみを削除
xticks((2:2:16),())

#minor ticks
minorticks_on()
locator_params(axis="x",nbins=4) # 細かさ

# 軸の数字を回転
labels = gca().get_yticklabels()
setp(labels, rotation=65);

ラベル

### x軸のラベルを任意に変更
xticks((0,pi/4,pi/2),(L"0",L"\frac{\pi}{4}",L"\frac{\pi}{2}"))

# mathbold
xlabel(L"\boldmath $M$")
ylabel(L"$M_z(H)/|$ {\boldmath $M$} $(0)|$")

#ラベルを消す
tick_params(labelbottom="off")

拡大図 inset

figure(figsize=(4,3),)

xx=[1:50]/5
plot(xx,xx.^2)

using PyCall
zoom= pyimport("mpl_toolkits.axes_grid1.inset_locator")
ax=gca()
ax=zoom.inset_axes(ax, width=2, height=2, loc=2,
                     bbox_to_anchor=(0., 0.),
                     bbox_transform=ax.figure.transFigure)
plot(xx,xx.^2,".")



ylim(0,20) #; ylim(ymax=20)
xlim(0,5)
xticks(fontsize=12)
yticks(fontsize=12)

ラベル位置を変更

# タイトル
title("Mean Field",fontsize=12, x=0.5, y=0.8)

# yラベル
gca().yaxis.set_label_coords(-0.15, -0.0)

数式中のハイフン

{\rm \mathchar`-}
12
9
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
12
9