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

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

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

    #!/usr/local/bin/python 

# encoding: utf-8 

""" 

plotting 

=============== 

:Summary: 

    Module of plotting functions 

 

:Author: 

    David Young 

 

:Date Created: 

    April 16, 2013 

 

:dryx syntax: 

    - ``xxx`` = come back here and do some more work 

    - ``_someObject`` = a 'private' object that should only be changed for debugging 

 

:Notes: 

    - If you have any questions requiring this script please email me: d.r.young@qub.ac.uk 

""" 

################# GLOBAL IMPORTS #################### 

# from _project_setup import * 

 

###################################################### 

# MAIN LOOP - USED FOR DEBUGGING OR WHEN SCRIPTING   # 

###################################################### 

def main(): 

    """ 

    The main function used when ``plotting`` run as a single script from the cl 

    """ 

    ################ > IMPORTS ################ 

    ## STANDARD LIB ## 

    ## THIRD PARTY ## 

    ## LOCAL APPLICATION ## 

    import dryxPython.commonutils as cu 

 

    dbConn, log = settings( 

        dbConn=False, 

        log=True) 

 

    ## START LOGGING ## 

    startTime = cu.get_now_sql_datetime() 

    log.info('--- STARTING TO RUN THE plotting AT %s' % (startTime,)) 

 

    ## WRITE CODE HERE 

 

    if dbConn: 

        dbConn.commit() 

        dbConn.close() 

    ## FINISH LOGGING ## 

    endTime = cu.get_now_sql_datetime() 

    runningTime = cu.calculate_time_difference(startTime, endTime) 

    log.info('-- FINISHED ATTEMPT TO RUN THE plotting AT %s (RUNTIME: %s) --' % (endTime, runningTime, )) 

 

    return 

 

################################################################### 

# CLASSES                                                         # 

################################################################### 

 

################################################################### 

# PUBLIC FUNCTIONS                                                # 

################################################################### 

## LAST MODIFIED : April 15, 2013 

## CREATED : April 15, 2013 

## AUTHOR : DRYX 

def plot_polynomial( 

        log, 

        title, 

        polynomialDict, 

        orginalDataDictionary=False, 

        pathToOutputPlotsFolder="~/Desktop", 

        xRange=False, 

        xlabel=False, 

        ylabel=False, 

        xAxisLimits=False, 

        yAxisLimits=False, 

        yAxisInvert=False, 

        prependNum=False, 

        legend=False): 

    """Plot a dictionary of numpy lightcurves polynomials 

 

    **Key Arguments:** 

        - ``log`` -- logger 

        - ``title`` -- title for the plot 

        - ``polynomialDict`` -- dictionary of polynomials { label01 : poly01, label02 : poly02 } 

        - ``orginalDataDictionary`` -- the orginal data points {name: [x, y]} 

        - ``pathToOutputPlotsFolder`` -- path the the output folder to save plot to 

        - ``xRange`` -- the x-range for the polynomial [xmin, xmax, interval] 

        - ``xlabel`` -- xlabel 

        - ``ylabel`` -- ylabel 

        - ``xAxisLimits`` -- the x-limits for the axes [xmin, xmax] 

        - ``yAxisLimits`` -- the y-limits for the axes [ymin, ymax] 

        - ``yAxisInvert`` -- invert the y-axis? Useful for lightcurves 

        - ``prependNum`` -- prepend this number to the output filename 

        - ``legend`` -- plot a legend? 

 

    **Return:** 

        - None 

    """ 

    ################ > IMPORTS ################ 

    ## STANDARD LIB ## 

    import sys 

    ## THIRD PARTY ## 

    import matplotlib.pyplot as plt 

    import numpy as np 

    ## LOCAL APPLICATION ## 

 

    ################ >ACTION(S) ################ 

    colors = [ 

        {'green' : '#859900'}, 

        {'blue' : '#268bd2'}, 

        {'red' : '#dc322f'}, 

        {'gray' : '#D2D1D1'}, 

        {'orange' : '#cb4b16'}, 

        {'violet' : '#6c71c4'}, 

        {'cyan' : '#2aa198'}, 

        {'magenta' : '#d33682'}, 

        {'yellow' : '#b58900'} 

    ] 

 

    if not xRange: 

        log.error('please provide an x-range') 

        sys.exit(1) 

 

    ax = plt.subplot(111) 

 

    if len(xRange) == 2: 

        xRange.append(1) 

 

    x = np.arange(xRange[0], xRange[1], xRange[2]) 

    if xAxisLimits: 

        ax.set_xlim(xAxisLimits[0], xAxisLimits[1]) 

    else: 

        overShoot = (xRange[1] - xRange[0])/10. 

        ax.set_xlim(xRange[0] - overShoot, xRange[1] + overShoot) 

    if yAxisLimits: 

        ax.set_ylim(yAxisLimits[0], yAxisLimits[1]) 

 

    theseColors = [ colors['blue'], colors['green'], colors['red'] ] 

 

    count = 0 

    if orginalDataDictionary: 

        for name, data in orginalDataDictionary.iteritems(): 

            ax.plot(data[0], data[1], '.', label=name, color=theseColors[count]) 

            count += 1 

            if count == 4: 

                count = 0 

 

    count = 0 

    for snType, poly in polynomialDict.iteritems(): 

        ax.plot(x, poly(x), label='%s' % (snType,), color=theseColors[count]) 

        count += 1 

        if count == 4: 

            count = 0 

 

    # Shink current axis by 20% 

    box = ax.get_position() 

    ax.set_position([box.x0, box.y0, box.width * 0.8, box.height]) 

    # Put a legend to the right of the current axis 

    if legend: 

        ax.legend(loc='center left', bbox_to_anchor=(1, 0.5), prop={'size':8}) 

    ax.titlesize = 'medium'   # fontsize of the axes title 

    ax.labelsize = 'medium'  # fontsize of the x any y labels 

 

    if xlabel: 

        plt.xlabel(xlabel, fontsize='small') 

    if ylabel: 

        plt.ylabel(ylabel, fontsize='small') 

    if title: 

        plt.title(title, fontsize='small', verticalalignment = 'bottom', linespacing = 0.2) 

 

    if yAxisInvert: 

        ax.invert_yaxis() 

 

    # fileName = pathToOutputPlotsFolder + title.replace(" ", "_") + ".ps" 

    # plt.savefig(fileName) 

    if prependNum: 

        title = "%02d_%s" % (prependNum, title) 

    thisTitle = title.replace(" ", "_") 

    thisTitle = thisTitle.replace("-", "_") 

    fileName = pathToOutputPlotsFolder + thisTitle + ".png" 

    imageLink = """ 

![%s_plot](%s) 

 

""" % (thisTitle, fileName) 

    plt.savefig(fileName) 

    plt.clf()  # clear figure 

 

    return imageLink 

 

 

## LAST MODIFIED : April 15, 2013 

## CREATED : April 15, 2013 

## AUTHOR : DRYX 

def plot_polar( 

        log, 

        title, 

        dataDictionary, 

        pathToOutputPlotsFolder="~/Desktop", 

        dataRange=False, 

        ylabel=False, 

        radius=False, 

        circumference=True, 

        circleTicksRange=(0, 360, 60), 

        circleTicksLabels=".", 

        prependNum=False): 

    """Plot a dictionary of numpy lightcurves polynomials 

 

    **Key Arguments:** 

        - ``log`` -- logger 

        - ``title`` -- title for the plot 

        - ``dataDictionary`` -- dictionary of data to plot { label01 : dataArray01, label02 : dataArray02 } 

        - ``pathToOutputPlotsFolder`` -- path the the output folder to save plot to 

        - ``dataRange`` -- the range for the data [min, max] 

        - ``ylabel`` -- ylabel 

        - ``radius`` -- the max radius of the plot 

        - ``circumference`` -- draw the circumference of the plot? 

        - ``circleTicksRange`` 

        - ``circleTicksLabels`` 

        - ``prependNum`` -- prepend this number to the output filename 

 

    **Return:** 

        - None 

    """ 

    ################ > IMPORTS ################ 

    ## STANDARD LIB ## 

    import sys 

    ## THIRD PARTY ## 

    import matplotlib.pyplot as plt 

    import numpy as np 

    ## LOCAL APPLICATION ## 

 

    ################ >ACTION(S) ################ 

    colors = [ 

        {'green' : '#859900'}, 

        {'blue' : '#268bd2'}, 

        {'red' : '#dc322f'}, 

        {'gray' : '#D2D1D1'}, 

        {'orange' : '#cb4b16'}, 

        {'violet' : '#6c71c4'}, 

        {'cyan' : '#2aa198'}, 

        {'magenta' : '#d33682'}, 

        {'yellow' : '#b58900'} 

    ] 

 

    # FORCE SQUARE FIGURE AND SQUARE AXES LOOKS BETTER FOR POLAR 

    fig = plt.figure( 

        num=None, 

        figsize=(8,8), 

        dpi=None, 

        facecolor=None, 

        edgecolor=None, 

        frameon=True) 

 

    ax = fig.add_axes( 

        [0.1, 0.1, 0.8, 0.8], 

        polar=True, 

        frameon=circumference) 

 

    ax.set_ylim(0, radius) 

    # ax.get_xaxis().set_visible(circumference) 

 

    if circleTicksRange: 

        circleTicks = np.arange(circleTicksRange[0], circleTicksRange[1], circleTicksRange[2]) 

    tickLabels = [] 

    for tick in circleTicks: 

        tickLabels.append(".") 

 

    plt.xticks(2*np.pi*circleTicks/360., tickLabels) 

 

    count = 0 

    for k, v in dataDictionary.iteritems(): 

        if count <= len(colors): 

            colorDict = colors[count] 

            count += 1 

        else: 

            count = 0 

            colorDict = colors[count] 

 

        thetaList = [] 

        twoPi = 2.*np.pi 

        for i in range(len(v)): 

            thetaList.append(twoPi*np.random.rand()) 

        thetaArray = np.array(thetaList) 

 

        x = thetaArray 

        y = v 

 

        plt.scatter( 

            x, 

            y, 

            label=k, 

            s=50, 

            c=colorDict.values(), 

            marker='o', 

            cmap=None, 

            norm=None, 

            vmin=None, 

            vmax=None, 

            alpha=0.5, 

            linewidths=None, 

            edgecolor='#657b83', 

            verts=None, 

            hold=True) 

 

    box = ax.get_position() 

    ax.set_position([box.x0, box.y0, box.width * 0.8, box.height]) 

    # Put a legend to the right of the current axis 

    ax.legend(loc='center left', bbox_to_anchor=(0.7, -0.1), prop={'size':8}) 

    plt.grid(True) 

    plt.title(title) 

    if prependNum: 

        title = "%02d_%s" % (prependNum, title) 

    thisTitle = title.replace(" ", "_") 

    thisTitle = thisTitle.replace("-", "_") 

    fileName = pathToOutputPlotsFolder + thisTitle + ".png" 

    imageLink = """ 

![%s_plot](%s) 

 

""" % (thisTitle, fileName) 

    plt.savefig(fileName) 

    plt.clf()  # clear figure 

 

    return imageLink 

 

 

 

################################################################### 

# PRIVATE (HELPER) FUNCTIONS                                      # 

################################################################### 

 

if __name__ == '__main__': 

    main() 

 

 

################################################################### 

# TEMPLATE FUNCTIONS                                              # 

###################################################################