Last active
March 6, 2023 12:32
-
-
Save naotohori/ec51322e954b918d7c5b09d08135cd06 to your computer and use it in GitHub Desktop.
Jupyter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%%writefile this_cell.txt | |
でそのセルの内容をそのまま出力。コードをターミナルで直接動かしたいときに使える。 | |
%matplotlib inline | |
#%matplotlib notebook | |
from IPython.display import display, HTML | |
display(HTML("<style>.container { width:80% !important; }</style>")) | |
import matplotlib.pyplot as plt | |
from matplotlib.colors import LogNorm | |
import matplotlib.patches as mpatches | |
import numpy as np | |
plt.rc('text', usetex=True) # To use bold font in LaTex | |
plt.rcParams['text.latex.preamble']=[r"\usepackage{amsmath}"] #To use bold font in LaTex | |
plt.rcParams['figure.autolayout']=True | |
plt.rcParams['figure.figsize'] = 5, 4 | |
plt.rcParams['figure.dpi'] = 300 | |
plt.rcParams['font.family'] ='sans-serif' #使用するフォントファミリー | |
plt.rcParams['font.serif'] = ['Tahoma'] | |
plt.rcParams['font.sans-serif'] = ['Arial', 'Helvetica'] #使用するフォント(探す順序) | |
plt.rcParams['xtick.direction'] = 'in' #x軸の目盛線が内向き('in')か外向き('out')か双方向か('inout') | |
plt.rcParams['ytick.direction'] = 'in' #y軸の目盛線が内向き('in')か外向き('out')か双方向か('inout') | |
plt.rcParams['xtick.major.width'] = 1.0 #x軸主目盛り線の線幅 | |
plt.rcParams['ytick.major.width'] = 1.0 #y軸主目盛り線の線幅 | |
plt.rcParams['font.size'] = 8 #フォントの大きさ | |
plt.rcParams['axes.linewidth'] = 1.0# 軸の線幅edge linewidth。囲みの太さ | |
plt.rcParams['savefig.dpi'] = 300 | |
plt.rcParams['savefig.bbox'] = 'tight' | |
plt.rcParams['savefig.pad_inches'] = 0.05 | |
plt.rcParams['savefig.transparent'] = True | |
## Output multiple-page PDF | |
from matplotlib.backends.backend_pdf import PdfPages | |
pdf = PdfPages('xxxx.pdf') | |
for _ in range(npages): | |
.... | |
pdf.savefig() | |
pdf.close() | |
## To prevent memory leak | |
%matplotlib | |
plt.ioff() | |
## Not draw top and right frame lines. | |
ax.spines['right'].set_visible(False) | |
ax.spines['top'].set_visible(False) | |
## Ticks | |
ax.set_ylim(0.0, 6.0) | |
ax.set_yticks([0,1,2,3,4,5]) | |
ax.yaxis.set_ticks_position('both') | |
# densely dotted | |
linestyle=(0,(1,1)) | |
# https://matplotlib.org/gallery/lines_bars_and_markers/linestyles.html | |
## Log scale | |
ax.set_xscale('log') | |
ax.set_xticks([0.1, 1, 10]) | |
ax.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter()) # This set ticklabels automatically. | |
#ax.set_xticklabels(('0.1','1','10')) # If you want to set labels manually. | |
ax.set_yticks([0,0.1,0.2,0.3]) | |
## Text | |
ax.text(-0.25, 1.05, '(a)', transform=ax.transAxes, size=10, weight='bold') | |
## Legend | |
ax.legend(fontsize=8, loc='upper left', bbox_to_anchor=(0.1, 0.95)) | |
# This puts the upper left corner of the legend box into (0.1,0.95) | |
## Vertical line | |
ax.axvline(x=0, ymin=0, ymax=1, **kwargs) | |
## Convert format | |
$ ipython nbconvert notebook.ipynb | |
This will be html (default) | |
$ ipython nbconvert --to FORMAT notebook.ipynb | |
FORMAT can be latex, pdf, slides, markdown, etc. | |
## Moving average | |
import numpy as np | |
N_MOVING_AVERAGE = 200 # Window size | |
ONES_MOVING_AVERAGE = np.ones((N_MOVING_AVERAGE,))/N_MOVING_AVERAGE | |
ax.plot(np.convolve(x, ONES_MOVING_AVERAGE, mode='valid'), | |
np.convolve(y, ONES_MOVING_AVERAGE, mode='valid'),) | |
################################################################## | |
## 2D histogram heatmap | |
ncols=1 | |
nrows=1 | |
fig, axs = plt.subplots(ncols=ncols, nrows=nrows, figsize=(3*ncols, 2.25*nrows), dpi=600) | |
ax = axs | |
etas = [] | |
thetas = [] | |
for l in open('angles.dat'): | |
lsp = l.split() | |
etas.append(float(lsp[1])) | |
thetas.append(float(lsp[2])) | |
print('Number of data points: %i' % len(etas)) | |
H, xedges, yedges = np.histogram2d(etas, thetas, bins=(180, 180), | |
range=[[0.,360.0],[0.,360.0]], density=True) | |
# H needs to be rotated and flipped | |
H = np.rot90(H) | |
H = np.flipud(H) | |
# Mask zeros | |
Hmasked = np.ma.masked_where(H==0,H) # Mask pixels with a value | |
ax.set_xlabel(r'$\eta$') | |
ax.set_ylabel(r'$\theta$') | |
ax.pcolormesh(xedges, yedges, Hmasked, cmap='rainbow') | |
ax.set_aspect('equal', adjustable='box') | |
fig.savefig('sample_2d_histogram_heatmap.png') | |
fig.savefig('sample_2d_histogram_heatmap.svg') | |
################################################################## | |
# Contact map | |
import pandas as pd | |
import seaborn as sns | |
cor_plots = range(13,207+1) # 13 ~ 207 (195) | |
df = pd.DataFrame(index=cor_plots, columns=cor_plots,dtype=float) | |
for cut in [7.3, 6.3]: | |
for K in [50, ]: | |
for Mg in Mg_calc: | |
for i in cor_plots: | |
df[i][i] = 1.0 | |
for l in open('./Mg_nt_nt_correlations/%i_%03i.K_bound_%3.1f.cor' % (K, Mg,cut)): | |
lsp = l.split() | |
i = int(lsp[0]) | |
j = int(lsp[1]) | |
c = float(lsp[2]) | |
df[i][j] = c | |
df[j][i] = c | |
# Set up the matplotlib figure | |
f, ax = plt.subplots(figsize=(4, 4)) | |
# Generate a custom diverging colormap | |
#cmap = sns.diverging_palette(220, 20, n=24, as_cmap=False) | |
cmap = sns.color_palette("RdBu_r", 24) | |
#cmap = sns.diverging_palette(220, 20, n=24) | |
# Draw the heatmap with the mask and correct aspect ratio | |
sns.heatmap(df, cmap=cmap, vmin=-1.0, vmax=1.0, center=0., | |
square=True, linewidths=.0, cbar_kws={"shrink": .8}) | |
ax.hlines(np.arange(20-12-0.5,210-12-0.5,10), *ax.get_ylim(),linewidths=0.1) | |
ax.vlines(np.arange(20-12-0.5,210-12-0.5,10), *ax.get_xlim(),linewidths=0.1) | |
ax.set_xticks(np.arange(20-12-0.5,210-12-0.5,10)) | |
ax.set_xticklabels(np.arange(20,210,10)) | |
ax.set_yticks(np.arange(20-12-0.5,210-12-0.5,10)) | |
ax.set_yticklabels(np.arange(20,210,10)) | |
ax.tick_params(direction='out', width=0.5) | |
f.savefig('%i_%03i.K_bound_%3.1f.png' % (K, Mg,cut)) | |
################################################################### | |
def draw_contact_map(H): | |
''' H is (N+1)x(N+1) matrix where index 0 is not used for data.''' | |
N = H.shape[0] - 1 | |
fig, axs = plt.subplots(1, 1, figsize=(3*1, 2.25*1), dpi=300) | |
ax = axs | |
edges = np.arange(0.5, N+0.5, 1.0) | |
# H needs to be rotated and flipped | |
H = np.rot90(H) | |
H = np.flipud(H) | |
hm = ax.pcolormesh(edges, edges, H[1:,1:], cmap='Greys') | |
ax.set_aspect('equal', adjustable='box') | |
ax.hlines(np.arange(10,N+1,10), *ax.get_ylim(),linewidths=0.1) | |
ax.vlines(np.arange(10,N+1,10), *ax.get_xlim(),linewidths=0.1) | |
ax.plot([0, 1], [0, 1], transform=ax.transAxes, linewidth=0.1) | |
ax.set_xlim(0.5,N+0.5) | |
ax.set_ylim(0.5,N+0.5) | |
ax.set_xticks(np.arange(10,N-0.5,10)) | |
ax.set_xticklabels(np.arange(10,N,10), fontsize=5) | |
ax.set_yticks(np.arange(10,N-0.5,10)) | |
ax.set_yticklabels(np.arange(10,N,10) , fontsize=5) | |
ax.tick_params(direction='out', width=0.2, length=2) | |
for axis in ['top','bottom','left','right']: | |
ax.spines[axis].set_linewidth(0.2) | |
return fig, ax |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment