質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
Matplotlib

MatplotlibはPythonのおよび、NumPy用のグラフ描画ライブラリです。多くの場合、IPythonと連携して使われます。

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Q&A

解決済

1回答

56337閲覧

python matplotlib グラフが表示されない

astromelt0416

総合スコア15

Matplotlib

MatplotlibはPythonのおよび、NumPy用のグラフ描画ライブラリです。多くの場合、IPythonと連携して使われます。

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

0グッド

1クリップ

投稿2018/05/11 11:00

編集2018/05/11 11:51

閲覧ありがとうございます。Python3でmatplotlibを用いてグラフを表示させたいのですが表示されなくて困っています。
各種サイトで検索かけて調べたのですが改善されないので詳しい方、教えていただけると助かります。plt.savefig()は正常に動作しておりグラフが保存されているため計算部分にミスはないと思われます。

発生している問題・エラーメッセージ

グラフが表示されない plt.show() が動いていない。

該当のソースコード

python3

T = Trange

plt.figure()
plt.plot(T, E, 'rx-')
plt.xlabel(r'Temperature $(\frac{J}{k_B})$')
plt.ylabel(r'$\langle E \rangle$ per site $(J)$')
plt.savefig("E8.pdf", format='pdf', bbox_inches='tight')

plt.figure()
plt.plot(T, SpcH, 'kx-')
plt.xlabel(r'Temperature $(\frac{J}{k_B})$')
plt.ylabel(r'$C_V$ per site $(\frac{J^2}{k_B^2})$')
plt.savefig("Cv8.pdf", format='pdf', bbox_inches='tight')

plt.figure()
plt.plot(T, M, 'bx-')
plt.xlabel(r'Temperature $(\frac{J}{k_B})$')
plt.ylabel(r'$\langle|M|\rangle$ per site $(\mu)$')
plt.savefig("M8.pdf", format='pdf', bbox_inches='tight')

plt.figure()
plt.plot(T, M_sus, 'gx-')
plt.xlabel(r'Temperature $(\frac{J}{k_B})$')
plt.ylabel(r'$\chi$ $(\frac{\mu}{k_B})$')
plt.savefig("chi8.pdf", format='pdf', bbox_inches='tight')

plt.tight_layout()
fig = plt.gcf()
plt.show()

np.savetxt('output.data',np.c_[T,E,SpcH,M,M_sus])

### 試したこと ここに問題に対して試したことを記載してください。 ### 補足情報(FW/ツールのバージョンなど)

python

1import matplotlib 2matplotlib.use('Agg') 3import numpy as np 4from numpy import linalg as LA 5import matplotlib.pyplot as plt 6 7L = 8 8ESTEP = 1000 9STEP = 10000 10 11J = 1 # J>0 to make it ferromagnetic 12 13# Intitialize the XY network 14def Init(): 15 return np.random.rand(L, L)*2*np.pi 16 #return np.ones([L, L]) 17 18# periodic neighbor 19def next(x): 20 if x == L-1: 21 return 0 22 else: 23 return x+1 24 25# construct the bond lattice 26def FreezeBonds(Ising,T,S): 27 iBondFrozen = np.zeros([L,L],dtype=int) 28 jBondFrozen = np.zeros([L,L],dtype=int) 29 for i in np.arange(L): 30 for j in np.arange(L): 31 freezProb_nexti = 1 - np.exp(-2 * J * S[i][j] * S[next(i)][j] / T) 32 freezProb_nextj = 1 - np.exp(-2 * J * S[i][j] * S[i][next(j)] / T) 33 if (Ising[i][j] == Ising[next(i)][j]) and (np.random.rand() < freezProb_nexti): 34 iBondFrozen[i][j] = 1 35 if (Ising[i][j] == Ising[i][next(j)]) and (np.random.rand() < freezProb_nextj): 36 jBondFrozen[i][j] = 1 37 return iBondFrozen, jBondFrozen 38 39# H-K algorithm to identify clusters 40def properlabel(prp_label,i): 41 while prp_label[i] != i: 42 i = prp_label[i] 43 return i 44 45# Swendsen-Wang cluster 46def clusterfind(iBondFrozen,jBondFrozen): 47 cluster = np.zeros([L, L],dtype=int) 48 prp_label = np.zeros(L**2,dtype=int) 49 label = 0 50 for i in np.arange(L): 51 for j in np.arange(L): 52 bonds = 0 53 ibonds = np.zeros(4,dtype=int) 54 jbonds = np.zeros(4,dtype=int) 55 56 # check to (i-1,j) 57 if (i > 0) and iBondFrozen[i-1][j]: 58 ibonds[bonds] = i-1 59 jbonds[bonds] = j 60 bonds += 1 61 # (i,j) at i edge, check to (i+1,j) 62 if (i == L-1) and iBondFrozen[i][j]: 63 ibonds[bonds] = 0 64 jbonds[bonds] = j 65 bonds += 1 66 # check to (i,j-1) 67 if (j > 0) and jBondFrozen[i][j-1]: 68 ibonds[bonds] = i 69 jbonds[bonds] = j-1 70 bonds += 1 71 # (i,j) at j edge, check to (i,j+1) 72 if (j == L-1) and jBondFrozen[i][j]: 73 ibonds[bonds] = i 74 jbonds[bonds] = 0 75 bonds += 1 76 77 # check and label clusters 78 if bonds == 0: 79 cluster[i][j] = label 80 prp_label[label] = label 81 label += 1 82 else: 83 minlabel = label 84 for b in np.arange(bonds): 85 plabel = properlabel(prp_label,cluster[ibonds[b]][jbonds[b]]) 86 if minlabel > plabel: 87 minlabel = plabel 88 89 cluster[i][j] = minlabel 90 # link to the previous labels 91 for b in np.arange(bonds): 92 plabel_n = cluster[ibonds[b]][jbonds[b]] 93 prp_label[plabel_n] = minlabel 94 # re-set the labels on connected sites 95 cluster[ibonds[b]][jbonds[b]] = minlabel 96 return cluster, prp_label 97 98# flip the cluster spins 99def flipCluster(Ising,cluster,prp_label): 100 for i in np.arange(L): 101 for j in np.arange(L): 102 # relabel all the cluster labels with the right ones 103 cluster[i][j] = properlabel(prp_label,cluster[i][j]) 104 sNewChosen = np.zeros(L**2) 105 sNew = np.zeros(L**2) 106 flips = 0 # get the number of flipped spins to calculate the Endiff and Magdiff 107 for i in np.arange(L): 108 for j in np.arange(L): 109 label = cluster[i][j] 110 randn = np.random.rand() 111 # mark the flipped label, use this label to flip all the cluster elements with this label 112 if (not sNewChosen[label]) and randn < 0.5: 113 sNew[label] = +1 114 sNewChosen[label] = True 115 elif (not sNewChosen[label]) and randn >= 0.5: 116 sNew[label] = -1 117 sNewChosen[label] = True 118 119 if Ising[i][j] != sNew[label]: 120 Ising[i][j] = sNew[label] 121 flips += 1 122 123 return Ising,flips 124 125# Swendsen-Wang Algorithm in Ising model (with coupling constant dependency on sites) 126# One-step for Ising 127def oneMCstepIsing(Ising, S): 128 [iBondFrozen, jBondFrozen] = FreezeBonds(Ising, T, S) 129 [SWcluster, prp_label] = clusterfind(iBondFrozen, jBondFrozen) 130 [Ising, flips] = flipCluster(Ising, SWcluster, prp_label) 131 return Ising 132 133# Decompose XY network to two Ising networks with project direction proj 134def decompose(XY,proj): 135 x = np.cos(XY) 136 y = np.sin(XY) 137 x_rot = np.multiply(x,np.cos(proj))+np.multiply(y,np.sin(proj)) 138 y_rot = -np.multiply(x,np.sin(proj))+np.multiply(y,np.cos(proj)) 139 Isingx = np.sign(x_rot) 140 Isingy = np.sign(y_rot) 141 S_x = np.absolute(x_rot) 142 S_y = np.absolute(y_rot) 143 return Isingx, Isingy, S_x, S_y 144 145# Compose two Ising networks to XY network 146def compose(Isingx_new,Isingy_new,proj,S_x, S_y): 147 x_rot_new = np.multiply(Isingx_new,S_x) 148 y_rot_new = np.multiply(Isingy_new,S_y) 149 x_new = np.multiply(x_rot_new,np.cos(proj))-np.multiply(y_rot_new,np.sin(proj)) 150 y_new = np.multiply(x_rot_new,np.sin(proj))+np.multiply(y_rot_new,np.cos(proj)) 151 XY_new = np.arctan2(y_new,x_new) 152 return XY_new 153 154def oneMCstepXY(XY): 155 proj = np.random.rand() 156 [Isingx, Isingy, S_x, S_y] = decompose(XY, proj) 157 Isingx_new = oneMCstepIsing(Isingx, S_x) 158 #Isingy_new = oneMCstepIsing(Isingy, S_y) 159 # Here we only use the flopping of Ising in projection direction, without the perpendicular direction 160 #XY_new = compose(Isingx_new, Isingy_new, proj, S_x, S_y) 161 XY_new = compose(Isingx_new, Isingy, proj, S_x, S_y) 162 return XY_new 163 164# Calculate the energy for XY network 165def EnMag(XY): 166 energy = 0 167 for i in np.arange(L): 168 for j in np.arange(L): 169 # energy 170 energy = energy - (np.cos(XY[i][j]-XY[(i-1)%L][j])+np.cos(XY[i][j]-XY[(i+1)%L][j])+np.cos(XY[i][j]-XY[i][(j-1)%L])+np.cos(XY[i][j]-XY[i][(j+1)%L])) 171 magx = np.sum(np.cos(XY)) 172 magy = np.sum(np.sin(XY)) 173 mag = np.array([magx,magy]) 174 return energy * 0.5, LA.norm(mag)/(L**2) 175 176# Swendsen Wang method for XY model 177def SWang(T): 178 XY = Init() 179 # thermal steps to get the equilibrium 180 for step in np.arange(ESTEP): 181 XY = oneMCstepXY(XY) 182 # finish with thermal equilibrium, and begin to calc observables 183 E_sum = 0 184 M_sum = 0 185 Esq_sum = 0 186 Msq_sum = 0 187 for step in np.arange(STEP): 188 XY = oneMCstepXY(XY) 189 [E,M] = EnMag(XY) 190 191 E_sum += E 192 M_sum += M 193 Esq_sum += E**2 194 Msq_sum += M**2 195 196 E_mean = E_sum/STEP/(L**2) 197 M_mean = M_sum/STEP 198 Esq_mean = Esq_sum/STEP/(L**4) 199 Msq_mean = Msq_sum/STEP 200 201 return XY, E_mean, M_mean, Esq_mean, Msq_mean 202 203M = np.array([])fig = plt.gcf() 204E = np.array([]) 205M_sus = np.array([]) 206SpcH = np.array([]) 207Trange = np.linspace(0.1, 2.5, 10) 208for T in Trange: 209 [Ising, E_mean, M_mean, Esq_mean, Msq_mean] = SWang(T) 210 M = np.append(M, np.abs(M_mean)) 211 E = np.append(E, E_mean) 212 M_sus = np.append(M_sus, 1/T*(Msq_mean-M_mean**2)) 213 SpcH = np.append(SpcH, 1/T**2*(Esq_mean-E_mean**2)) 214 215# plot the figures 216T = Trange 217 218plt.figure() 219plt.plot(T, E, 'rx-') 220plt.xlabel(r'Temperature $(\frac{J}{k_B})$') 221plt.ylabel(r'$\langle E \rangle$ per site $(J)$') 222plt.savefig("E8.pdf", format='pdf', bbox_inches='tight') 223 224plt.figure() 225plt.plot(T, SpcH, 'kx-') 226plt.xlabel(r'Temperature $(\frac{J}{k_B})$') 227plt.ylabel(r'$C_V$ per site $(\frac{J^2}{k_B^2})$') 228plt.savefig("Cv8.pdf", format='pdf', bbox_inches='tight') 229 230plt.figure() 231plt.plot(T, M, 'bx-') 232plt.xlabel(r'Temperature $(\frac{J}{k_B})$') 233plt.ylabel(r'$\langle|M|\rangle$ per site $(\mu)$') 234plt.savefig("M8.pdf", format='pdf', bbox_inches='tight') 235 236plt.figure() 237plt.plot(T, M_sus, 'gx-') 238plt.xlabel(r'Temperature $(\frac{J}{k_B})$') 239plt.ylabel(r'$\chi$ $(\frac{\mu}{k_B})$') 240plt.savefig("chi8.pdf", format='pdf', bbox_inches='tight') 241 242plt.tight_layout() 243fig = plt.gcf() 244plt.show() 245 246np.savetxt('output.data',np.c_[T,E,SpcH,M,M_sus]) 247 248

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

同じような経験を以前しました。そのときは確か、ここの方法で解決しました。

matplotlibが描画されない - DISTRICT 37

REPLでimport _tkinterって打ってimportできなかったら、この方法が手っ取り早いと思います。

importできればmatplotlib側の設定でなんとかなる希望もなくはないです。

追記

手元で動かした結果、figure1~4の窓が出てきました。

python

1import matplotlib.pyplot as plt 2import numpy as np 3T = np.arange(10) 4E = np.arange(10) 5SpcH = np.arange(10) 6M = np.arange(10) 7M_sus = np.arange(10) 8 9plt.figure() 10plt.plot(T, E, 'rx-') 11plt.xlabel(r'Temperature $(\frac{J}{k_B})$') 12plt.ylabel(r'$\langle E \rangle$ per site $(J)$') 13plt.savefig("E8.pdf", format='pdf', bbox_inches='tight') 14 15plt.figure() 16plt.plot(T, SpcH, 'kx-') 17plt.xlabel(r'Temperature $(\frac{J}{k_B})$') 18plt.ylabel(r'$C_V$ per site $(\frac{J^2}{k_B^2})$') 19plt.savefig("Cv8.pdf", format='pdf', bbox_inches='tight') 20 21plt.figure() 22plt.plot(T, M, 'bx-') 23plt.xlabel(r'Temperature $(\frac{J}{k_B})$') 24plt.ylabel(r'$\langle|M|\rangle$ per site $(\mu)$') 25plt.savefig("M8.pdf", format='pdf', bbox_inches='tight') 26 27plt.figure() 28plt.plot(T, M_sus, 'gx-') 29plt.xlabel(r'Temperature $(\frac{J}{k_B})$') 30plt.ylabel(r'$\chi$ $(\frac{\mu}{k_B})$') 31plt.savefig("chi8.pdf", format='pdf', bbox_inches='tight') 32 33plt.tight_layout() 34fig = plt.gcf() 35plt.show()

In non-interactive mode, display all figures and block until the figures have been closed; in interactive mode it has no effect unless figures were created prior to a change from non-interactive to interactive mode (not recommended). In that case it displays the figures but does not block.

matplotlib.pyplot.show — Matplotlib 2.2.2 documentation

まさかこの処理の前にインタラクティブモードとか使ってたりします?

投稿2018/05/11 11:10

編集2018/05/11 11:31
hayataka2049

総合スコア30933

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

astromelt0416

2018/05/11 11:17

回答ありがとうございます。 ほかのコードではmatplotlibでグラフを描いて表示ことができる状態なのですが・・・ このコード上の問題ではないということですか?
hayataka2049

2018/05/11 11:25

えーっと、他のコードなら普通にplt.show()でウィンドウが立ち上がって見ることができる、ということでよろしいですか? jupyterとかで見てるのではなく? それなら環境の問題はないでしょう(たぶん) 回答に追記します
astromelt0416

2018/05/11 11:31

返信ありがとうございます。その認識で間違いありません。
hayataka2049

2018/05/11 11:33

とりあえず私の手元で問題が再現していないので、私が追記に書いたコードをコピペして実行してみて、これでも出ないかどうか確認してください
astromelt0416

2018/05/11 11:37

hayataka2049様のコードを試してみたのですが、グラフは正常に表示されました・・・
hayataka2049

2018/05/11 11:48

掲載されていない上の方に何か悪さをしている奴がいるのでしょう・・・他にmatplotlibを用いる処理を行っていますか? 公開して差し支えなければ、すべて掲載していただくのが一番手っ取り早いと思います(質問本文に追記してください)。そうでなければ、出せる範囲で何やってるか教えて頂ければ
astromelt0416

2018/05/11 11:48

質問文にコードの全文を貼りました。もしよろしければ参照していただけると幸いです。
hayataka2049

2018/05/11 11:58 編集

最初の二行だった・・・ matplotlib 画像が表示されない | せんべいって美味しいよね http://clc.gonna.jp/2017/05/matplotlib-%E7%94%BB%E5%83%8F%E3%81%8C%E8%A1%A8%E7%A4%BA%E3%81%95%E3%82%8C%E3%81%AA%E3%81%84/ import matplotlib matplotlib.use('Agg') を import matplotlib matplotlib.use('TkAgg') に変更してみる。デフォルトでTkAggな気がするのでこの二行コメントアウトしても(つーか消しても)たぶん動きます。 それで解決しませんか?
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問