Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1# SPDX-FileCopyrightText: 2020 Jonathan Pieper <jpieper@stud.uni-frankfurt.de> 

2# 

3# SPDX-License-Identifier: GPL-3.0-or-later 

4 

5# -*- coding: utf-8 -*- 

6""" 

7Main parent class for all plotting classes. 

8 

9""" 

10 

11import logging # System Modules 

12import os 

13 

14# Basic Plotting libraries 

15import matplotlib 

16from matplotlib import cm 

17import matplotlib.pyplot as plt 

18import seaborn as sns 

19import numpy as np 

20 

21 

22class PlottingClass(object): 

23 """Defines the basic plotting style.""" 

24 

25 def __init__(self, **style): 

26 """ 

27 Args: 

28 **style: 

29 """ 

30 default_style = { 

31 'dpi': 300, 

32 'figure.autolayout': False, 

33 'figsize': (8, 6), 

34 'axes.labelsize': 18, 

35 'axes.titlesize': 20, 

36 'font.size': 16, 

37 'lines.linewidth': 2.0, 

38 'lines.markersize': 8, 

39 'legend.fontsize': 14, 

40 'mpl_style': False, 

41 'latex': True, 

42 'default_cm': cm.Blues, 

43 } 

44 

45 self.name = 'Default Plotting Class' 

46 self.style = default_style 

47 self.set_style(**style) 

48 

49 get = lambda self, *key: self.style.get(*key) 

50 

51 __repr__ = lambda self: '%s\n' % self.name 

52 

53 __str__ = lambda self: '%s\n' % self.name + \ 

54 '\n'.join(['%s:\t%s' % (key, val) for key, val in self.style.items()]) 

55 

56 def update(self, other): 

57 

58 """ 

59 Args: 

60 other: 

61 """ 

62 self.style.update(other) 

63 

64 def __setitem__(self, key, value): 

65 """ 

66 Args: 

67 key: 

68 value: 

69 """ 

70 self.update(dict(key=value)) 

71 

72 def __add__(self, other): 

73 self.update(other) 

74 

75 # Set Plotting Style 

76 def set_style(self, **style): 

77 """ 

78 Sets the Style for plots 

79  

80 :param size: A dictionary of parameters or the name of a preconfigured set. 

81 :type size: dict, None, or one of {paper, notebook, talk, poster} 

82 

83 :param style: 

84 :type style: dict, None, or one of {darkgrid, whitegrid, dark, white, ticks} 

85  

86 :param default: if True it sets default 

87 :code:`size=talk` and 

88 :code:`style=whitegrid` 

89 :type default: bool 

90 

91 :param notebook: if True it sets default 

92 :code:`size=notebook` and 

93 :code:`style=ticks` 

94 

95 :type notebook: bool 

96 

97  

98 Returns 

99 ------- 

100 None. 

101  

102 """ 

103 self.style.update(style) 

104 if self.get('default'): 

105 def_size = 'talk' 

106 def_style = 'whitegrid' 

107 elif self.get('notebook'): 

108 def_size = 'notebook' 

109 def_style = 'ticks' 

110 else: 

111 def_size = 'talk' 

112 def_style = 'whitegrid' 

113 

114 sns.set(self.get('size', def_size), 

115 self.get('style', def_style), 

116 self.get('palette', 'deep'), 

117 self.get('font', 'sans-serif'), 

118 self.get('font-scale', 1)) 

119 

120 if style.get('grid'): 

121 plt.rcParams['axes.grid'] = True 

122 plt.rcParams['grid.linestyle'] = '--' 

123 

124 latex = 'latex' in self.style 

125 plt.rcParams['text.usetex'] = latex 

126 if latex: # True activates latex output in fonts! 

127 plt.rcParams[ 

128 'text.latex.preamble'] = '' 

129 

130 if self.get('set_mpl_params', False): 

131 params = style.get('mpl_params', { 

132 'figure.dpi': self.get('dpi', 300), 

133 'savefig.dpi': self.get('dpi', 300), 

134 'figure.figsize': self.get('figsize'), 

135 'figure.autolayout': False, 

136 'axes.labelsize': 18, 

137 'axes.titlesize': 20, 

138 'font.size': 16, 

139 'lines.linewidth': 2.0, 

140 'lines.markersize': 8, 

141 'legend.fontsize': 14, 

142 'figure.subplot.hspace': 0.3, 

143 'figure.subplot.wspace': 0.3, 

144 'savefig.transparent': False, 

145 'savefig.bbox': 'tight', 

146 'savefig.pad_inches': 0.1, 

147 }) 

148 update_keys = ['figure.autolayout', 

149 'axes.labelsize', 

150 'axes.titlesize', 

151 'font.size', 

152 'lines.linewidth', 

153 'lines.markersize', 

154 'legend.fontsize'] 

155 params.update({ 

156 update_keys[key]: self.get(update_keys[key]) \ 

157 for key in np.argwhere([_ in style \ 

158 for _ in update_keys]).ravel() 

159 }) 

160 matplotlib.rcParams.update(params) 

161 

162 if self.get('mpl_style'): 

163 matplotlib.style.use(self.get('mpl_style')) 

164 

165 def get_style(self, custom=None): 

166 """ 

167 Args: 

168 custom: 

169 """ 

170 if custom: 

171 return plt.style.context(custom) 

172 return plt.style.context(self.get('mpl_style')) 

173 

174 def set_plot_settings(self, **kwargs): 

175 """ 

176 Args: 

177 **kwargs: 

178 """ 

179 plt.xscale(kwargs.get('xscale', 'log')) 

180 plt.yscale(kwargs.get('yscale', 'log')) 

181 

182 xmin, xmax = kwargs.get('xlim', (None, None)) 

183 ymin, ymax = kwargs.get('ylim', (None, None)) 

184 if xmin: 

185 plt.xlim(xmin, xmax) 

186 if ymin: 

187 plt.ylim(ymin, ymax) 

188 if not kwargs.get('legend_settings'): 

189 plt.legend(loc=kwargs.get('legend_location', 'best')) 

190 else: 

191 plt.legend(**kwargs.get('legend_settings')) 

192 

193 if kwargs.get('grid'): 

194 plt.grid(b=True, **kwargs['grid']) 

195 

196 title = kwargs.get('title') 

197 if title: 

198 plt.title(title) 

199 

200 xlabel = kwargs.get('xlabel', '$f$ [Hz]') 

201 ylabel = kwargs.get('ylabel', '$S_{V_H}$ [${V^2}$/{Hz}]') 

202 plt.xlabel(xlabel) 

203 plt.ylabel(ylabel) 

204 

205 def draw_oneoverf(self, ax, **kwargs): 

206 # Draw 1/f 

207 """ 

208 Args: 

209 ax: 

210 **kwargs: 

211 """ 

212 xmin = kwargs.get('xmin', .1) 

213 ymin = kwargs.get('ymin', 1e-6) 

214 factor = kwargs.get('factor', 10) 

215 alpha = kwargs.get('alpha', 1) 

216 if kwargs.get('plot_label'): 

217 label = kwargs.get('plot_label') 

218 elif alpha == 1: 

219 label = '$1/f$' 

220 else: 

221 label = '$1/f^%s$' % alpha 

222 

223 mean_x = kwargs.get('mean_x', (xmin * np.sqrt(factor))) 

224 mean_y = kwargs.get('mean_y', (ymin / (factor ** (alpha / 2)))) 

225 if not (kwargs.get('disable')): 

226 ax.plot([xmin, xmin * factor], [ymin, ymin / (factor ** alpha)], 

227 kwargs.get('plot_style', 'k--'), label=label, linewidth=2) 

228 ax.annotate(label, (mean_x, mean_y), 

229 color=kwargs.get('an_color', 'black'), 

230 size=kwargs.get('an_size', 16)) 

231 

232 def save_plot(self, fname, fext='png'): 

233 """Saves the current plot as file. 

234 

235 Args: 

236 fname (str): Filename 

237 fext (str): Extension 

238 

239 Returns: 

240 None 

241 """ 

242 

243 if not os.path.exists(fname): 

244 os.makedirs(fname) 

245 

246 if fext == 'pgf': 

247 matplotlib.rcParams.update({ 

248 "pgf.texsystem": "pdflatex", 

249 'font.family': 'serif', 

250 'text.usetex': True, 

251 'pgf.rcfonts': False, 

252 'text.latex.preamble': r'\usepackage[utf8]{inputenc}\DeclareUnicodeCharacter{2212}{-}' 

253 }) 

254 plt.savefig('%s.%s' % (fname, fext), backend='pgf') 

255 plt.show() 

256 

257 else: 

258 plt.show() 

259 plt.savefig('%s.%s' % (fname, fext))