A good MWE for Python plots in physics
Here is a python code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
### matplotlib package -- https://matplotlib.org/stable/index.html ###
import matplotlib.pyplot as plt
### numpy package -- https://numpy.org/doc/stable/ ###
import numpy as np
### scipy package -- https://docs.scipy.org/doc/scipy/ ###
import scipy.constants as const
from scipy import optimize as opt # for optimization and fit -- https://docs.scipy.org/doc/scipy/reference/tutorial/optimize.html
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.size'] = 11
plt.rcParams['text.usetex'] = True
plt.rcParams['text.latex.preamble'] = r'''
\usepackage{physics}
\usepackage{siunitx}
'''
def main():
### IMPORT DATA ###
### ----------- ###
DATA_DIR = 'filename.txt'
X, X_error, Y, Y_error = np.loadtxt(DATA_DIR,
usecols=(0,1,2,3),
dtype=np.dtype([('X', float),
('X_error', float),
('Y', float),
('Y_error', float)
]),
unpack=True)
### PLOT ###
### ---- ###
fig, ax = plt.subplots()
plt.plot(X, Y, color='tab:blue', linewidth=1.0, label='X vs. Y')
plt.errorbar(X, Y, xerr=X_error, yerr=Y_error, fmt='.', ecolor='tab:red', elinewidth=1.0, label='error bars')
plt.xlabel(r'$X$ in \si{\meter}')
plt.ylabel(r'$Y$ in \si{\second}')
plt.title(r'Some Title')
plt.legend(loc='upper right')
plt.grid(True)
filename = 'X-vs_Y'
fig.savefig(filename + '.eps', format='eps', bbox_inches='tight')
fig.savefig(filename + '.pdf', format='pdf', bbox_inches='tight')
fig.savefig(filename + '.png', format='png', bbox_inches='tight', dpi=250)
fig.savefig(filename + '.svg', format='svg', bbox_inches='tight')
if __name__ == "__main__":
main()