def overlay_png(canvas, png_path, data, data2=None, gm=None, scale=.75, template=None, continents=1): canvas.open() canvas.put_png_on_canvas(png_path, zoom=scale) is_portrait = canvas.size < 1 if template: t = vcs.createtemplate(template) else: t = vcs.createtemplate() padding = (1 - scale) / 2. # Plot & outline t.data.priority = 10 t.data.x1 = padding t.data.x2 = 1 - padding t.data.y1 = padding t.data.y2 = 1 - padding t.box1.x1 = padding t.box1.x2 = 1 - padding t.box1.y1 = padding t.box1.y2 = 1 - padding # Ticks ticlen = abs(t.xtic1.y2 - t.xtic1.y1) t.xtic1.y1 = padding t.xtic1.y2 = padding - ticlen t.ytic1.x1 = padding t.ytic1.x2 = padding - ticlen / 2. t.xtic2.y1 = 1 - padding t.xtic2.y2 = 1 - (padding - ticlen / 2.) t.ytic2.x1 = 1 - padding t.ytic2.x2 = 1 - (padding - ticlen / 2.) # Tick Labels t.xlabel1.y = t.xtic1.y2 - ticlen t.xlabel2.y = t.xtic2.y2 + ticlen t.ylabel1.x = t.ytic1.x2 - ticlen / 2. t.ylabel2.x = t.ytic2.x2 + ticlen / 2. # Axis labels t.xname.y = t.xlabel1.y - ticlen * 2 t.yname.x = t.ylabel1.x - ticlen * 2 # Legend if is_portrait: t.legend.x1 = t.data.x1 t.legend.x2 = t.data.x2 t.legend.y1 = t.data.y1 / 4. t.legend.y2 = t.legend.y1 + padding / 3. else: t.legend.x1 = t.data.x2 + padding / 4. t.legend.x2 = t.legend.x1 + padding / 4. t.legend.y1 = t.data.y1 t.legend.y2 = t.data.y2 plot_args = [data, data2, t, gm] kwargs = {"continents": continents} return canvas.plot(*[p for p in plot_args if p is not None], **kwargs)
def save(self, name=None): if name is None: sync_template(self.real_tmpl, self.tmpl) self.editedTemplate.emit(self.real_tmpl) else: template = vcs.createtemplate(name, self.tmpl.name) self.createdTemplate.emit(template)
def __init__(self, tmpl, parent=None): super(TemplateEditorDialog, self).__init__(parent=parent) self.real_tmpl = tmpl self.tmpl = vcs.createtemplate(source=tmpl) l = QtGui.QVBoxLayout() self.editor = TemplateEditor() self.editor.setTemplate(self.tmpl) l.addWidget(self.editor) buttons = QtGui.QHBoxLayout() cancel = QtGui.QPushButton("Cancel") cancel.clicked.connect(self.reject) save_as = QtGui.QPushButton("Save As") save_as.clicked.connect(self.customName) save = QtGui.QPushButton("Save") save.clicked.connect(self.accept) self.accepted.connect(self.save) save.setDefault(True) buttons.addWidget(cancel, alignment=QtCore.Qt.AlignLeft) buttons.addStretch() buttons.addWidget(save_as) buttons.addWidget(save) l.addLayout(buttons) self.setLayout(l)
def test_MeanValue(self): filename = 'tas_Amon_IPSL-CM5A-LR_1pctCO2_r1i1p1_185001-198912.nc' if not os.path.exists(filename): r = requests.get( "https://cdat.llnl.gov/cdat/sample_data/notebooks/{}".format(filename), stream=True) with open(filename, "wb") as f: for chunk in r.iter_content(chunk_size=1024): if chunk: # filter local_filename keep-alive new chunks f.write(chunk) # Open data file and extract variable f = cdms2.open(filename) data = f("tas") # Mask the data datamskd = MV2.masked_greater(data, data.max()-7) # extract the departures of the masked data. datamskd_departures = cdutil.times.ANNUALCYCLE.departures(datamskd) # create time series of the masked data departures. datamskd_departures_ts = genutil.averager(datamskd_departures, axis='xy', weights=[ 'weighted', 'weighted'], combinewts=1) datamskd_departures_ts_corrected = cdutil.times.ANNUALCYCLE.departures( datamskd_departures_ts) # Graphics and plot steps template = vcs.createtemplate() self.x = vcs.init(bg=True, geometry=(1200, 900)) # Plot image and check against reference self.x.clear() self.x.plot(datamskd_departures_ts_corrected, template) self.checkImage("test_vcs_plot_mean_value.png")
def update(self): if self.canvas is None: return self.canvas.clear(render=False) template = vcs.createtemplate() template.blank() template.legend.priority = 1 # Expand template to engulf the canvas template.legend.x1 = .125 template.legend.y1 = .35 template.legend.x2 = .875 template.legend.y2 = .65 legend_size = 50 text_orientation = vcs.createtextorientation() text_orientation.height = legend_size text_orientation.halign = "center" template.legend.textorientation = text_orientation.name template.drawColorBar(self.legend.vcs_colors, self.legend.levels, self.legend.labels, ext_1=self.legend.ext_left, ext_2=self.legend.ext_right, x=self.canvas, cmap=self.legend.colormap, style=[self.legend.fill_style], index=self.legend._gm.fillareaindices, opacity=self.legend._gm.fillareaopacity) self.canvas.backend.renWin.Render()
def update(self): if self.backend.renWin and self.interactor is None: self.interactor = self.backend.renWin.GetInteractor() if self.interactor is not None: self.listeners.append(self.interactor.AddObserver("TimerEvent", self.animate)) self.listeners.append(self.interactor.AddObserver("LeftButtonPressEvent", self.click)) self.listeners.append(self.interactor.AddObserver("MouseMoveEvent", self.hover)) self.listeners.append(self.interactor.AddObserver("LeftButtonReleaseEvent", self.release)) self.init_buttons() self.init_toolbar() self.displays = [vcs.elements["display"][display] for display in self.canvas.display_names] for display in self.displays: if display._template_origin in self.templates: continue if display.ratio is not None: # Ratio'd displays already have a temporary template self.templates[display.template] = display._template_origin else: # Manufacture a placeholder template to use for updates new_template = vcs.createtemplate(source=display.template) self.templates[new_template.name] = display.template display.template = new_template.name # This is an attribute used internally; might break display._template_origin = new_template.name
def testRatioOne(self): t = vcs.createtemplate() t.ratio(1) self.assertClose(t.data.x1, 0.276658462196) self.assertClose(t.data.y1, 0.259999990463) self.assertClose(t.data.x2, 0.723341526628) self.assertClose(t.data.y2, 0.860000014305)
def update(self): if self.canvas is None: return self.canvas.clear(render=False) template = vcs.createtemplate() template.blank() template.legend.priority = 1 # Expand template to engulf the canvas template.legend.x1 = 0.125 template.legend.y1 = 0.35 template.legend.x2 = 0.875 template.legend.y2 = 0.65 legend_size = 50 text_orientation = vcs.createtextorientation() text_orientation.height = legend_size text_orientation.halign = "center" template.legend.textorientation = text_orientation.name template.drawColorBar( self.legend.vcs_colors, self.legend.levels, self.legend.labels, ext_1=self.legend.ext_left, ext_2=self.legend.ext_right, x=self.canvas, cmap=self.legend.colormap, style=[self.legend.fill_style], index=self.legend._gm.fillareaindices, opacity=self.legend._gm.fillareaopacity, ) self.canvas.backend.renWin.Render()
def templ_from_json(blob): t = vcs.createtemplate() for a in blob: if isinstance(blob[a], dict): attr = getattr(t, a) for k in blob[a]: setattr(attr, k, blob[a][k]) return t
def loadTemplate(nm,vals): try: t = vcs.gettemplate(nm) except: t = vcs.createtemplate(nm) for k,v in vals.iteritems(): A = getattr(t,k) for a,v in v.iteritems(): setattr(A,a,v)
def update(self): if self.canvas is None: return self.canvas.clear(render=False) template = vcs.createtemplate(source=self.axis.tmpl) template.blank() axis_orientation = self.axis._axis[0] axis_number = self.axis._axis[1] axis_ticks = getattr(template, "%stic%s" % (axis_orientation, axis_number)) axis_min_ticks = getattr( template, "%smintic%s" % (axis_orientation, axis_number)) axis_labels = getattr(template, "%slabel%s" % (axis_orientation, axis_number)) # Make the ticks visible axis_ticks.priority = 1 axis_min_ticks.priority = 1 if self.axis.show_miniticks else 0 axis_labels.priority = 1 moving_attr = "x" if axis_orientation == "y" else "y" attr_1 = moving_attr + "1" attr_2 = moving_attr + "2" ticklen = getattr(axis_ticks, attr_2) - getattr(axis_ticks, attr_1) label_distance = getattr(axis_labels, moving_attr) - getattr( axis_ticks, attr_1) minticklen = getattr(axis_min_ticks, attr_2) - getattr( axis_min_ticks, attr_1) # Move the ticks to the middle setattr(axis_ticks, attr_1, .5) setattr(axis_ticks, attr_2, .5 + ticklen) setattr(axis_min_ticks, attr_1, .5) setattr(axis_min_ticks, attr_2, .5 + minticklen) setattr(axis_labels, moving_attr, .5 + label_distance) # Get the worldcoordinates try: wc = vcs.utils.getworldcoordinates(self.axis.gm, self.axis.var.getAxis(-1), self.axis.var.getAxis(-2)) except: # 1D wc = vcs.utils.getworldcoordinates(self.axis.gm, range(len(self.axis.var)), self.axis.var) template.drawTicks(self.axis.var, self.axis.gm, self.canvas, axis_orientation, axis_number, (template.data.x1, template.data.x2, template.data.y1, template.data.y2), wc) self.canvas.backend.renWin.Render()
def testRemoveTo(self): #canvas = vcs.init() nto = vcs.listelements("textorientation") nt = vcs.listelements("template") t = vcs.createtemplate() t.scalefont(.6) # canvas.removeobect(t) vcs.removeobject(t) nto2 = vcs.listelements("textorientation") nt2 = vcs.listelements("template") self.assertEqual(len(nto2), len(nto)) self.assertEqual(len(nt2), len(nt))
def editors(): box = vcs.createboxfill() tmpl = vcs.createtemplate() var = cdms2.open(vcs.sample_data + "/clt.nc")("clt") axis = VCSAxis(box, tmpl, "y1", var) edit_1 = AxisEditorWidget("x") edit_1.setAxisObject(axis) edit_2 = AxisEditorWidget("y") edit_2.setAxisObject(axis) return (edit_1, edit_2)
def editors(): box = vcs.createboxfill() tmpl = vcs.createtemplate() var = cdms2.open(vcs.sample_data + "/clt.nc")("clt") axis = vcsaxis.VCSAxis(box, tmpl, "y1", var) edit_1 = AxisEditor.AxisEditorWidget("x") edit_1.setAxisObject(axis) edit_2 = AxisEditor.AxisEditorWidget("y") edit_2.setAxisObject(axis) return (edit_1, edit_2)
def diagnostics_template(): """creates and returns a VCS template suitable for diagnostics plots""" if 'diagnostic' in vcs.listelements('template'): tm = vcs.gettemplate('diagnostic') else: tm = vcs.createtemplate( 'diagnostic', 'default' ) # ...creates a template named 'diagnostic', as a copy of the one named 'default'. tm.title.x = 0.5 to = vcs.createtextorientation() to.halign = 'center' tm.title.textorientation = to tm.dataname.priority = 0 tm.units.priority = 0 return tm
def testVCSreset1only(self): for gtype in vcs.listelements(): b0 = vcs.listelements(gtype) if gtype == 'colormap': b = vcs.createcolormap() xtra = vcs.createisofill() untouched = vcs.listelements("isofill") elif gtype == "template": b = vcs.createtemplate() elif gtype == "textcombined": b = vcs.createtextcombined() elif gtype == "textorientation": b = vcs.createtextorientation() elif gtype == "texttable": b = vcs.createtexttable() elif gtype == "fillarea": b = vcs.createfillarea() elif gtype == "projection": b = vcs.createprojection() elif gtype == "marker": b = vcs.createmarker() elif gtype == "line": b = vcs.createline() elif gtype in ["display", "font", "fontNumber", "list", "format"]: vcs.manageElements.reset() continue else: b = vcs.creategraphicsmethod(gtype) if gtype != "colormap": xtra = vcs.createcolormap() untouched = vcs.listelements("colormap") b1 = vcs.listelements(gtype) self.assertNotEqual(b0, b1) vcs.manageElements.reset(gtype) b2 = vcs.listelements(gtype) self.assertEqual(b0, b2) if gtype == "colormap": self.assertEqual(untouched, vcs.listelements("isofill")) else: self.assertEqual(untouched, vcs.listelements("colormap")) vcs.manageElements.reset() if gtype == "colormap": self.assertNotEqual(untouched, vcs.listelements("isofill")) else: self.assertNotEqual(untouched, vcs.listelements("colormap")) # case for 1d weirdness sc = vcs.createscatter() vcs.manageElements.reset()
def plotminmax(outpath, mins, maxs, varname): canvas = vcs.init() gm = vcs.create1d() mn, mx = vcs.minmax(mins, maxs) gm.datawc_y1 = mn gm.datawc_y2 = mx template = vcs.createtemplate() template.scale(.95) template.move(.05, 'x') template.blank(["max", "mean"]) canvas.plot(mins, gm, template, id=varname) template = vcs.createtemplate() template.scale(.95) template.move(.05, 'x') template.blank(["min", "mean"]) canvas.plot(maxs, gm, template, id=varname) canvas.png(outpath) canvas.clear()
def setTemplate(self, template): if isinstance(template, dict): my_tmpl = vcs.createtemplate() for attr in template: if attr == "name": continue if attr == "p_name": continue for key in template[attr]: if key == "member": continue tmpl_attr = getattr(my_tmpl, attr) new_val = template[attr][key] setattr(tmpl_attr, key, new_val) else: my_tmpl = vcs.gettemplate(str(template)) self._plot.template = my_tmpl
def setUp(self): f = cdms2.open(os.path.join(cdat_info.get_sampledata_path(), "clt.nc")) s = f("clt", slice(0, 1)) self.x = vcs.init(bg=True, geometry=(800, 600)) b = vcs.createboxfill() t = vcs.createtemplate() to = vcs.createtextorientation() to.angle = 90 t.xlabel1.textorientation = to b.xticlabels1 = {45: "45N"} b.datawc_x1 = -180 b.datawc_x2 = 180. self.b = b self.t = t self.x.plot(s, b, t) self.x.png("testClick") self.s = s
def test_pcoord(self): import vcs import vcsaddons J = self.loadJSON() rms_xyt = J(statistic=["rms_xyt"], season=["ann"], region="global")(squeeze=1) x = vcs.init(geometry=(1200, 600), bg=bg) gm = vcsaddons.createparallelcoordinates(x=x) t = vcs.createtemplate() to = x.createtextorientation() to.angle = -45 to.halign = "right" t.xlabel1.textorientation = to.name t.reset('x', 0.05, 0.9, t.data.x1, t.data.x2) #t.reset('y',0.5,0.9,t.data.y1,t.data.y2) ln = vcs.createline() ln.color = [[0, 0, 0, 0]] t.legend.line = ln t.box1.priority = 0 t.legend.x1 = .91 t.legend.x2 = .99 t.legend.y1 = t.data.y1 t.legend.y2 = t.data.y2 # Set variable name rms_xyt.id = "RMS" # Set units of each variables on axis rms_xyt.getAxis(-2).units = [ "mm/day", "mm/day", "hPa", "W/m2", "W/m2", "W/m2", "K", "K", "K", "m/s", "m/s", "m/s", "m/s", "m" ] # Sets title rms_xyt.title = "Annual Mean Error" gm.plot(rms_xyt, template=t, bg=bg) src = os.path.join(os.path.dirname(__file__), "testParallelCoordinates.png") print src fnm = os.path.join(os.getcwd(), "testParallelCoordinates.png") x.png(fnm) ret = vcs.testing.regression.check_result_image(fnm, src) if ret != 0: sys.exit(ret)
def update(self): if self.canvas is None: return self.canvas.clear(render=False) template = vcs.createtemplate(source=self.axis.tmpl) template.blank() axis_orientation = self.axis._axis[0] axis_number = self.axis._axis[1] axis_ticks = getattr(template, "%stic%s" % (axis_orientation, axis_number)) axis_min_ticks = getattr(template, "%smintic%s" % (axis_orientation, axis_number)) axis_labels = getattr(template, "%slabel%s" % (axis_orientation, axis_number)) # Make the ticks visible axis_ticks.priority = 1 axis_min_ticks.priority = 1 if self.axis.show_miniticks else 0 axis_labels.priority = 1 moving_attr = "x" if axis_orientation == "y" else "y" attr_1 = moving_attr + "1" attr_2 = moving_attr + "2" ticklen = getattr(axis_ticks, attr_2) - getattr(axis_ticks, attr_1) label_distance = getattr(axis_labels, moving_attr) - getattr(axis_ticks, attr_1) minticklen = getattr(axis_min_ticks, attr_2) - getattr(axis_min_ticks, attr_1) # Move the ticks to the middle setattr(axis_ticks, attr_1, .5) setattr(axis_ticks, attr_2, .5 + ticklen) setattr(axis_min_ticks, attr_1, .5) setattr(axis_min_ticks, attr_2, .5 + minticklen) setattr(axis_labels, moving_attr, .5 + label_distance) # Get the worldcoordinates try: wc = vcs.utils.getworldcoordinates(self.axis.gm, self.axis.var.getAxis(-1), self.axis.var.getAxis(-2)) except: # 1D wc = vcs.utils.getworldcoordinates(self.axis.gm, range(len(self.axis.var)), self.axis.var) template.drawTicks(self.axis.var, self.axis.gm, self.canvas, axis_orientation, axis_number, (template.data.x1, template.data.x2, template.data.y1, template.data.y2), wc) self.canvas.backend.renWin.Render()
def test_pcoord(self): import vcs import vcsaddons J=self.loadJSON() rms_xyt = J(statistic=["rms_xyt"],season=["ann"],region="global")(squeeze=1) x=vcs.init(geometry=(1200,600),bg=bg) gm = vcsaddons.createparallelcoordinates(x=x) t = vcs.createtemplate() to=x.createtextorientation() to.angle=-45 to.halign="right" t.xlabel1.textorientation = to.name t.reset('x',0.05,0.9,t.data.x1,t.data.x2) #t.reset('y',0.5,0.9,t.data.y1,t.data.y2) ln = vcs.createline() ln.color = [[0,0,0,0]] t.legend.line = ln t.box1.priority=0 t.legend.x1 = .91 t.legend.x2 = .99 t.legend.y1 = t.data.y1 t.legend.y2 = t.data.y2 # Set variable name rms_xyt.id = "RMS" # Set units of each variables on axis rms_xyt.getAxis(-2).units = ["mm/day","mm/day","hPa","W/m2","W/m2","W/m2", "K","K","K","m/s","m/s","m/s","m/s","m"] # Sets title rms_xyt.title = "Annual Mean Error" gm.plot(rms_xyt,template=t,bg=bg) src = os.path.join(os.path.dirname(__file__), "testParallelCoordinates.png") print src fnm = os.path.join(os.getcwd(), "testParallelCoordinates.png") x.png(fnm) ret = vcs.testing.regression.check_result_image( fnm, src) if ret != 0: sys.exit(ret)
def update(self): if self.backend.renWin and self.interactor is None: self.interactor = self.backend.renWin.GetInteractor() if self.interactor is not None: self.listeners.append( self.interactor.AddObserver( "TimerEvent", self.animate)) self.listeners.append( self.interactor.AddObserver( "LeftButtonPressEvent", self.click)) self.listeners.append( self.interactor.AddObserver( "MouseMoveEvent", self.hover)) self.listeners.append( self.interactor.AddObserver( "LeftButtonReleaseEvent", self.release)) self.init_buttons() self.init_toolbar() self.displays = [vcs.elements["display"][display] for display in self.canvas.display_names] for display in self.displays: if display._template_origin in self.templates: continue if display.ratio is not None: # Ratio'd displays already have a temporary template self.templates[display.template] = display._template_origin else: # Manufacture a placeholder template to use for updates new_template = vcs.createtemplate(source=display.template) self.templates[new_template.name] = display.template display.template = new_template.name # This is an attribute used internally; might break display._template_origin = new_template.name
def test_pcoord(self): import vcs import vcsaddons J=self.loadJSON() rms_xyt = J(statistic=["rms_xyt"],season=["ann"],region="global")(squeeze=1) gm = vcsaddons.createparallelcoordinates(x=self.x) t = vcs.createtemplate() to = vcs.createtextorientation() to.angle=-45 to.halign="right" t.xlabel1.textorientation = to.name t.data.list() t.reset('x',0.05,0.9,t.data.x1,t.data.x2) t.data.list() #t.reset('y',0.5,0.9,t.data.y1,t.data.y2) ln = vcs.createline() ln.color = [[0,0,0,0]] t.legend.line = ln t.box1.priority=0 t.legend.x1 = .91 t.legend.x2 = .99 t.legend.y1 = t.data.y1 t.legend.y2 = t.data.y2 # Set variable name rms_xyt.id = "RMS" # Set units of each variables on axis rms_xyt.getAxis(-2).units = ["mm/day","mm/day","hPa","W/m2","W/m2","W/m2", "K","K","K","m/s","m/s","m/s","m/s","m"] # Sets title rms_xyt.title = "Annual Mean Error" gm.plot(rms_xyt,template=t) fnm = os.path.join(os.getcwd(), "testParallelCoordinates.png") self.checkImage(fnm)
import os, sys, cdms2, vcs, vcs.testing.regression as regression # Load the clt data: dataFile = cdms2.open(os.path.join(vcs.sample_data, "clt.nc")) clt = dataFile("clt") clt = clt(latitude=(-90.0, 90.0), longitude=(-180., 175.), squeeze=1, time=('1979-1-1 0:0:0.0', '1988-12-1 0:0:0.0')) # Initialize canvas: canvas = regression.init() t1 = vcs.createtemplate() t1.scale(.5, "y") t1.move(-.15, "y") t2 = vcs.createtemplate(source=t1.name) t2.move(.5, 'y') canvas.plot(clt, t1, continents=0, bg=True) canvas.plot(clt, t2, continents=1, bg=True) regression.run(canvas, "test_vcs_no_continents.png")
os.remove("test_vcs_dump_json.json") b = vcs.createboxfill("vcs_instance") b.script("test_vcs_dump_json","a") b = vcs.createisofill("vcs_instance") b.script("test_vcs_dump_json","a") b = vcs.createisoline("vcs_instance") b.script("test_vcs_dump_json","a") b = vcs.createmeshfill("vcs_instance") b.script("test_vcs_dump_json","a") b = vcs.create1d("vcs_instance") b.script("test_vcs_dump_json","a") b = vcs.createfillarea("vcs_instance") b.script("test_vcs_dump_json","a") b = vcs.createvector("vcs_instance") b.script("test_vcs_dump_json","a") b = vcs.createtext("vcs_instance") b.script("test_vcs_dump_json","a") b = vcs.createline("vcs_instance") b.script("test_vcs_dump_json","a") b = vcs.createmarker("vcs_instance") b.script("test_vcs_dump_json","a") b = vcs.createtemplate("vcs_instance") b.script("test_vcs_dump_json","a") b = vcs.createprojection("vcs_instance") b.script("test_vcs_dump_json","a") assert(filecmp.cmp("test_vcs_dump_json.json", src))
import vcsaddons import os, sys, vcs, vcs.testing.regression as regression x = vcs.init() x.drawlogooff() x.setantialiasing(0) bg = True t = vcs.createtemplate() t.drawLinesAndMarkersLegend(x, ["red","blue","green"], ["solid","dash","dot"],[1,4,8], ["blue","green","red"], ["cross","square","dot"],[3,4,5], ["sample A","type B","thing C"],bg=bg,render=True) fnm = "test_drawLinesAndMarkersLegend.png" x.png(fnm) src = sys.argv[1] ret = regression.check_result_image(fnm, src) sys.exit(ret)
# Zero out the array so we can see the continents clearly clt[:] = 0 # Initialize canvas: canvas = regression.init() # Create and plot quick boxfill with default settings: boxfill = canvas.createboxfill() # Change the type boxfill.boxfill_type = 'custom' # Set levels to ignore 0 boxfill.levels = [1, 100] # Pick a color, any color boxfill.fillareacolors = [242] dataonly = vcs.createtemplate() dataonly.blank() dataonly.data.priority = 1 multitemplate = EzTemplate.Multi(template=dataonly, rows=4, columns=3) line_styles = ['long-dash', 'dot', 'dash', 'dash-dot', 'solid'] for i in range(12): cont_index = i % 6 + 1 cont_line = vcs.createline() cont_line.width = i % 3 + 1 cont_line.type = line_styles[i % 5] print "Cont_line_rtype:",line_styles[i % 5] cont_line.color = i + 200
def plot(self, data=None, mesh=None, template=None, meshfill=None, x=None, bg=0, multiple=1.1): self.bg = bg # Create the vcs canvas if x is not None: self.x = x # Continents bug # x.setcontinentstype(0) # gets the thing to plot ! if data is None: data = self.get() # Do we use a predefined template ? if template is None: template = self.generateTemplate() else: if isinstance(template, vcs.template.P): tid = template.name elif isinstance(template, str): tid = template else: raise 'Error cannot understand what you mean by template=' + \ str(template) template = vcs.createtemplate(source=tid) # Do we use a predefined meshfill ? if meshfill is None: mtics = {} for i in range(100): mtics[i - .5] = '' meshfill = vcs.createmeshfill() meshfill.xticlabels1 = eval(data.getAxis(1).names) meshfill.yticlabels1 = eval(data.getAxis(0).names) meshfill.datawc_x1 = -.5 meshfill.datawc_x2 = data.shape[1] - .5 meshfill.datawc_y1 = -.5 meshfill.datawc_y2 = data.shape[0] - .5 meshfill.mesh = self.PLOT_SETTINGS.draw_mesh meshfill.missing = self.PLOT_SETTINGS.missing_color meshfill.xticlabels2 = mtics meshfill.yticlabels2 = mtics if self.PLOT_SETTINGS.colormap is None: self.set_colormap() elif self.x.getcolormapname() != self.PLOT_SETTINGS.colormap: self.x.setcolormap(self.PLOT_SETTINGS.colormap) if self.PLOT_SETTINGS.levels is None: min, max = vcs.minmax(data) if max != 0: max = max + .000001 levs = vcs.mkscale(min, max) else: levs = self.PLOT_SETTINGS.levels if len(levs) > 1: meshfill.levels = levs if self.PLOT_SETTINGS.fillareacolors is None: if self.PLOT_SETTINGS.colormap is None: # Default colormap only use range 16->40 cols = vcs.getcolors(levs, list(range(16, 40)), split=1) else: cols = vcs.getcolors(levs, split=1) meshfill.fillareacolors = cols else: meshfill.fillareacolors = self.PLOT_SETTINGS.fillareacolors # Now creates the mesh associated n = int(multiple) ntot = int((multiple - n) * 10 + .1) sh = list(data.shape) sh.append(2) Indx = MV2.indices((sh[0], sh[1])) Y = Indx[0] X = Indx[1] if ntot == 1: sh.append(4) M = MV2.zeros(sh) M[:, :, 0, 0] = Y - .5 M[:, :, 1, 0] = X - .5 M[:, :, 0, 1] = Y - .5 M[:, :, 1, 1] = X + .5 M[:, :, 0, 2] = Y + .5 M[:, :, 1, 2] = X + .5 M[:, :, 0, 3] = Y + .5 M[:, :, 1, 3] = X - .5 M = MV2.reshape(M, (sh[0] * sh[1], 2, 4)) elif ntot == 2: sh.append(3) M = MV2.zeros(sh) M[:, :, 0, 0] = Y - .5 M[:, :, 1, 0] = X - .5 M[:, :, 0, 1] = Y + .5 - (n - 1) M[:, :, 1, 1] = X - 0.5 + (n - 1) M[:, :, 0, 2] = Y + .5 M[:, :, 1, 2] = X + .5 M = MV2.reshape(M, (sh[0] * sh[1], 2, 3)) elif ntot == 3: design = int((multiple - n) * 100 + .1) if design == 33: sh.append(3) M = MV2.zeros(sh) if n == 1: M[:, :, 0, 0] = Y - .5 M[:, :, 1, 0] = X - .5 M[:, :, 0, 1] = Y + .5 M[:, :, 1, 1] = X M[:, :, 0, 2] = Y + .5 M[:, :, 1, 2] = X - .5 elif n == 2: M[:, :, 0, 0] = Y - .5 M[:, :, 1, 0] = X - .5 M[:, :, 0, 1] = Y + .5 M[:, :, 1, 1] = X M[:, :, 0, 2] = Y - .5 M[:, :, 1, 2] = X + .5 elif n == 3: M[:, :, 0, 0] = Y + .5 M[:, :, 1, 0] = X + .5 M[:, :, 0, 1] = Y + .5 M[:, :, 1, 1] = X M[:, :, 0, 2] = Y - .5 M[:, :, 1, 2] = X + .5 M = MV2.reshape(M, (sh[0] * sh[1], 2, 3)) elif design == 32: sh.append(5) M = MV2.zeros(sh) M[:, :, 0, 0] = Y M[:, :, 1, 0] = X d = .5 / MV2.sqrt(3.) if n == 1: M[:, :, 0, 1] = Y + .5 M[:, :, 1, 1] = X M[:, :, 0, 2] = Y + .5 M[:, :, 1, 2] = X - .5 M[:, :, 0, 3] = Y - d M[:, :, 1, 3] = X - .5 # dummy point for n==1 or 3 M[:, :, 0, 4] = Y M[:, :, 1, 4] = X if n == 2: M[:, :, 0, 1] = Y - d M[:, :, 1, 1] = X - .5 M[:, :, 0, 2] = Y - .5 M[:, :, 1, 2] = X - .5 M[:, :, 0, 3] = Y - .5 M[:, :, 1, 3] = X + .5 M[:, :, 0, 4] = Y - d M[:, :, 1, 4] = X + .5 elif n == 3: M[:, :, 0, 1] = Y + .5 M[:, :, 1, 1] = X M[:, :, 0, 2] = Y + .5 M[:, :, 1, 2] = X + .5 M[:, :, 0, 3] = Y - d M[:, :, 1, 3] = X + .5 # dummy point for n==1 or 3 M[:, :, 0, 4] = Y M[:, :, 1, 4] = X M = MV2.reshape(M, (sh[0] * sh[1], 2, 5)) else: sh.append(5) M = MV2.zeros(sh) M[:, :, 0, 0] = Y M[:, :, 1, 0] = X d = 1. / 3. if n == 1: M[:, :, 0, 1] = Y + .5 M[:, :, 1, 1] = X M[:, :, 0, 2] = Y + .5 M[:, :, 1, 2] = X - .5 M[:, :, 0, 3] = Y - d M[:, :, 1, 3] = X - .5 # dummy point for n==1 or 3 M[:, :, 0, 4] = Y M[:, :, 1, 4] = X if n == 2: M[:, :, 0, 1] = Y - d M[:, :, 1, 1] = X - .5 M[:, :, 0, 2] = Y - .5 M[:, :, 1, 2] = X - .5 M[:, :, 0, 3] = Y - .5 M[:, :, 1, 3] = X + .5 M[:, :, 0, 4] = Y - d M[:, :, 1, 4] = X + .5 elif n == 3: M[:, :, 0, 1] = Y + .5 M[:, :, 1, 1] = X M[:, :, 0, 2] = Y + .5 M[:, :, 1, 2] = X + .5 M[:, :, 0, 3] = Y - d M[:, :, 1, 3] = X + .5 # dummy point for n==1 or 3 M[:, :, 0, 4] = Y M[:, :, 1, 4] = X M = MV2.reshape(M, (sh[0] * sh[1], 2, 5)) elif ntot == 4: sh.append(3) M = MV2.zeros(sh) M[:, :, 0, 0] = Y M[:, :, 1, 0] = X if n == 1: M[:, :, 0, 1] = Y + .5 M[:, :, 1, 1] = X + .5 M[:, :, 0, 2] = Y + .5 M[:, :, 1, 2] = X - .5 elif n == 2: M[:, :, 0, 1] = Y + .5 M[:, :, 1, 1] = X - .5 M[:, :, 0, 2] = Y - .5 M[:, :, 1, 2] = X - .5 elif n == 3: M[:, :, 0, 1] = Y - .5 M[:, :, 1, 1] = X - .5 M[:, :, 0, 2] = Y - .5 M[:, :, 1, 2] = X + .5 elif n == 4: M[:, :, 0, 1] = Y - .5 M[:, :, 1, 1] = X + .5 M[:, :, 0, 2] = Y + .5 M[:, :, 1, 2] = X + .5 M = MV2.reshape(M, (sh[0] * sh[1], 2, 3)) else: if isinstance(meshfill, vcs.meshfill.P): tid = mesh.id elif isinstance(meshfill, str): tid = mesh else: raise 'Error cannot understand what you mean by meshfill=' + \ str(meshfill) meshfill = vcs.createmeshfill(source=tid) if mesh is None: mesh = M raveled = MV2.ravel(data) self.x.plot(raveled, mesh, template, meshfill, bg=self.bg) # If required plot values if self.PLOT_SETTINGS.values.show: self.draw_values(raveled, mesh, meshfill, template) # Now prints the rest of the title, etc... # but only if n==1 if n == 1: axes_param = [] for a in data.getAxis(0).id.split('___'): axes_param.append(a) for a in data.getAxis(1).id.split('___'): axes_param.append(a) nparam = 0 for p in self.parameters_list: if p not in self.dummies and \ p not in self.auto_dummies and \ p not in axes_param: nparam += 1 if self.verbose: print('NPARAM:', nparam) if nparam > 0: for i in range(nparam): j = MV2.ceil(float(nparam) / (i + 1.)) if j <= i: break npc = i # number of lines npl = int(j) # number of coulmns if npc * npl < nparam: npl += 1 # computes space between each line dl = (.95 - template.data.y2) / npl dc = .9 / npc npci = 0 # counter for columns npli = 0 # counter for lines for p in self.parameters_list: if p not in self.dummies and \ p not in self.auto_dummies and \ p not in axes_param: txt = self.x.createtext( None, self.PLOT_SETTINGS.parametertable.name, None, self.PLOT_SETTINGS.parameterorientation.name) value = getattr(self, p) if (isinstance(value, (list, tuple)) and len(value) == 1): txt.string = p + ':' + \ str(self.makestring(p, value[0])) display = 1 elif isinstance(value, (str, int, float)): txt.string = p + ':' + \ str(self.makestring(p, value)) display = 1 else: display = 0 if display: # Now figures out where to put these... txt.x = [(npci) * dc + dc / 2. + .05] txt.y = [1. - (npli) * dl - dl / 2.] npci += 1 if npci >= npc: npci = 0 npli += 1 if p in list(self.altered.keys()): dic = self.altered[p] if dic['size'] is not None: txt.size = dic['size'] if dic['color'] is not None: txt.color = dic['color'] if dic['x'] is not None: txt.x = dic['x'] if dic['y'] is not None: txt.y = dic['y'] self.x.plot(txt, bg=self.bg, continents=0) if self.PLOT_SETTINGS.time_stamp is not None: sp = time.ctime().split() sp = sp[:3] + [sp[-1]] self.PLOT_SETTINGS.time_stamp.string = ''.join(sp) self.x.plot( self.PLOT_SETTINGS.time_stamp, bg=self.bg, continents=0) if self.PLOT_SETTINGS.logo is not None: self.PLOT_SETTINGS.logo.plot(self.x, bg=self.bg) return mesh, template, meshfill
""" An example demonstrating the use of templates, as well as the importance of setting levels appropriately for your visualization. """ vcs.download_sample_data_files() # Let's use an aspect ratio of 2:1 width/height canvas = vcs.init(size=2) cdmsfile = cdms2.open(vcs.sample_data + "/geos5-sample.nc") # Extend the longitude to wrap around sphu = cdmsfile("sphu", longitude=(0, 360)) # Create a base template and place all of the labels that we want root_template = vcs.createtemplate("reduced") root_template.blank(["mean", "max", "min", "zvalue", "dataname", "crtime", "ytic2", "xtic2"]) # Shrink data and box1 a little horizontally root_template.data.x2 -= .05 root_template.box1.x2 -= .05 # Move the legend to the right side root_template.legend.x1 = root_template.data.x2 + .01 root_template.legend.x2 = root_template.data.x2 + .03 root_template.legend.y1 = root_template.data.y1 root_template.legend.y2 = root_template.data.y2 # Create a left/top aligned textorientation for the labels textorientation = vcs.createtextorientation() textorientation.halign = 'left'
def spaghetti_plot(variables, template=None, min_y=None, max_y=None, left_label=None, right_label=None, tick_sides=None, line="default", marker="default", x_labels="*", y_labels="*", canvas=None): """ This file is ready to be imported by your scripts, and you can just call this function. Sample usage is below. variables: List of variables to plot template: The template to use as the base for the plot. min_y: If you want to adjust the y axis bounds, you can set a minimum value. Will be derived from data if not specified. max_y: If you want to adjust the y axis bounds, you can set a maximum value. Will be derived from data if not specified. left_label: Text to put on the left Y axis right_label: Text to put on the right Y axis tick_sides: A list of "left" or "right" values indicating which side of the chart you want the variable axes to be displayed. line: A line object or name of a line object used to describe the lines plotted. Set to None to hide. marker: A marker object or name of a marker object used to describe the markers plotted. Set to None to hide. x_labels: Dictionary for setting axis tick labels y_labels: Dictionary for setting axis tick labels """ if canvas is None: canvas = vcs.init() if isinstance(template, (str, unicode)): template = vcs.gettemplate(template) if template is None: # Use our custom default template for 1ds template = vcs.createtemplate() # Shrink the template a bit template.scale(.78, "x") template.move(.02, "x") template.yname.x = .01 template.data.y1 = .1 template.box1.y1 = .1 ticlen = template.xtic1.y2 - template.xtic1.y1 template.xtic1.y1 = template.data.y1 template.xtic1.y2 = template.xtic1.y1 + ticlen template.xtic2.priority = 0 template.xlabel1.y = template.xtic1.y2 - .01 template.legend.x1 = template.data.x2 + (1 - template.data.x2) / 3. template.legend.x2 = .95 template.legend.y1 = template.data.y1 template.legend.y2 = template.data.y2 template.yname.y = (template.data.y1 + template.data.y2) / 2. template.xname.y = template.xlabel1.y - .05 # The labels don't make any sense with multiple values; hide them. template.min.priority = 0 template.max.priority = 0 template.mean.priority = 0 template.dataname.priority = 0 templates = EzTemplate.oneD(len(variables), template=template) templates.x = canvas if tick_sides is None: tick_sides = ["left"] * len(variables) clean_ticks = [] for t in tick_sides: if t.lower() not in ('left', 'right'): raise ValueError( "tick_sides must be a list of 'left' or 'right' values; found '%s'." % t) clean_ticks.append(t.lower()) tick_sides = clean_ticks if len(tick_sides) < len(variables): tick_sides += tick_sides[-1:] * len(variables) # Store min/max per side for appropriate scaling min_vals = {"left": min_y, "right": min_y} if min_y is None: for i, var in enumerate(variables): v_min = min(var) min_y = min_vals[tick_sides[i]] if min_y is None or min_y > v_min: min_vals[tick_sides[i]] = v_min max_vals = {"left": max_y, "right": max_y} if max_y is None: for i, var in enumerate(variables): v_max = max(var) max_y = max_vals[tick_sides[i]] if max_y is None or max_y < v_max: max_vals[tick_sides[i]] = v_max if isinstance(line, (str, unicode)): line = vcs.getline(line) if isinstance(marker, (str, unicode)): marker = vcs.getmarker(marker) to_pad = [] if line is not None: widths = line.width to_pad.append(widths) styles = line.type to_pad.append(styles) colors = line.color to_pad.append(colors) if marker is not None: markers = marker.type to_pad.append(markers) marker_colors = marker.color to_pad.append(marker_colors) marker_sizes = marker.size to_pad.append(marker_sizes) for padded in to_pad: if len(padded) < len(variables): padded += padded[-1:] * (len(variables) - len(padded)) for n in range(len(variables)): gm = vcs.create1d() if line is not None: gm.line = styles[n] gm.linewidth = widths[n] gm.linecolor = colors[n] else: gm.linewidth = 0 if marker is not None: gm.marker = markers[n] gm.markersize = marker_sizes[n] gm.markercolor = marker_colors[n] else: gm.marker = None gm.datawc_y1 = min_vals[tick_sides[n]] gm.datawc_y2 = max_vals[tick_sides[n]] template = templates.get(n) gm.xticlabels1 = x_labels if tick_sides[n] == "left": if tick_sides.index("left") == n: template.ylabel1.priority = 1 if left_label is not None: template.yname.priority = 0 left_text = vcs.createtext( Tt_source=template.yname.texttable, To_source=template.yname.textorientation) left_text.x = template.yname.x left_text.y = template.yname.y left_text.string = [left_label] templates.x.plot(left_text) else: template.ylabel1.priority = 0 template.yname.priority = 0 template.ylabel2.priority = 0 gm.yticlabels1 = y_labels gm.yticlabels2 = "" else: template.ylabel1.priority = 0 if tick_sides.index("right") == n: template.ylabel2.priority = 1 if right_label is not None: right_text = vcs.createtext( Tt_source=template.yname.texttable, To_source=template.yname.textorientation) right_text.x = template.data.x2 + (template.data.x1 - template.yname.x) right_text.y = template.yname.y right_text.string = [right_label] templates.x.plot(right_text) else: template.ylabel2.priority = 0 gm.yticlabels1 = "" gm.yticlabels2 = y_labels if n != 0: template.xlabel1.priority = 0 template.xname.priority = 0 var = variables[n] templates.x.plot(var, gm, template) return templates.x
def createtemplate(self, templateName, nameSource): """Creates a template with name 'templateName' using 'nameSource' as the base template""" base_template = vcs.gettemplate(nameSource) vcs.createtemplate(templateName, base_template)
outline = vcs.createline(source="default") outline.viewport = fa.viewport outline.x = x outline.y = y canvas.plot(fa) canvas.plot(outline) if __name__ == "__main__": #datafile = cdms2.open(vcs.sample_data + "/tas_mo.nc") #var = datafile("tas") datafile = cdms2.open(vcs.sample_data + "/clt.nc") var = datafile('clt') left_tmpl = vcs.createtemplate("left") left_tmpl.scale(.5, "x") left_tmpl.move(-.02, "x") right_tmpl = vcs.createtemplate("right", left_tmpl) right_tmpl.move(.5, "x") canvas = vcs.init() canvas.bgX = 1500 canvas.bgY = 750 levs = levels(var, partition_count=10) stat_iso = vcs.createisofill() int_levs = [] for l in levs:
import vcs, cdms2 x = vcs.init() f = cdms2.open(vcs.sample_data + "/clt.nc") base_iso = vcs.createisofill("base") base_iso.levels = range(0, 101, 10) t = vcs.createtemplate("base") x.plot(f("clt"), t, base_iso) pattern_iso = vcs.createisofill("patterned", base_iso) pattern_iso.fillareastyle = "pattern" pattern_iso.fillareaindices = range(1, 11) # Just draw the legend and the data t2 = vcs.createtemplate("just_data", t.name) t2.blank() t2.data.priority = 1 t2.legend.priority = 1 x.plot(f("clt"), t2, pattern_iso) fname = raw_input("Save?") if fname: x.png(fname)
def plot(self, array, template=None, bg=False, render=True, x=None): """Parallel Coordinates plot array must be of shape: (...,Dim1,Nlines) """ if not array.ndim > 1: raise Exception("Array must be at least 2D") nlines = array.shape[-1] length = array.shape[-2] # Pad attributes related to Y axis for att in ["datawc_y1", "datawc_y2", "yticlabels"]: # prepare local lists exec("%s = list(self.%s)" % (att, att)) exec("while len(%s) < length: %s+=[%s[-1]]" % (att, att, att)) data = array.asma() maxs = numpy.ma.max(data, axis=-1) mins = numpy.ma.min(data, axis=-1) if template is not None: t = vcs.createtemplate(source=template) else: t = vcs.createtemplate(source=self.template) for i in range(length): levels = vcs.mkscale(mins[i], maxs[i]) # Do we need to create our range if numpy.allclose(datawc_y1[i], 1.e20): # noqa datawc_y1[i] = levels[0] # noqa datawc_y2[i] = levels[-1] # noqa maxs[i] = datawc_y2[i] # noqa mins[i] = datawc_y1[i] # noqa # Do we have tics? if yticlabels[i] == "*": # noqa yticlabels[i] = vcs.mklabels(levels) # noqa if x is None: x = self.x self.drawYAxes(mins, maxs, yticlabels, t, x, bg) # noqa ax = array.getAxis(-2) deflbls = {} for i in range(length): deflbls[float(i) / (length - 1)] = str(ax[i]) if hasattr(ax, "units") and isinstance(ax.units, (list, tuple)): deflbls[float(i) / (length - 1)] += " (%s)" % ax.units[i] if self.xticlabels1 == "*": lbls1 = deflbls else: lbls1 = self.xticlabels1 if self.xmtics1 == "": lbls1m = deflbls else: lbls1m = self.xmtics1 if self.xticlabels2 == "*": lbls2 = deflbls else: lbls2 = self.xticlabels2 if self.xmtics2 == "": lbls2m = deflbls else: lbls2m = self.xmtics2 for l_tmp, lbls in enumerate([lbls1, lbls1m, lbls2, lbls2m]): ln = x.createline(source=t.xtic1.line) xs = [] ys = [] if l_tmp % 2 == 0: if l_tmp == 0: txt = x.createtext(To_source=t.xlabel1.textorientation, Tt_source=t.xlabel1.texttable) else: txt = x.createtext(To_source=t.xlabel2.textorientation, Tt_source=t.xlabel2.texttable) txs = [] tys = [] ts = [] for loc in lbls: xs.append([loc, loc]) if l_tmp == 0: ys.append([t.xtic1.y1, t.xtic1.y2]) txs.append(loc) tys.append(t.xlabel1.y) ts.append(lbls[loc]) ln.priority = t.xtic1.priority txt.priority = t.xlabel1.priority elif l_tmp == 1: ys.append([t.xmintic1.y1, t.xmintic1.y2]) ln.priority = t.xmintic1.priority elif l_tmp == 2: ys.append([t.xtic2.y1, t.xtic2.y2]) txs.append(loc) tys.append(t.xlabel2.y) ts.append(lbls[loc]) ln.priority = t.xtic2.priority txt.priority = t.xlabel2.priority elif l_tmp == 3: ys.append([t.xmintic2.y1, t.xmintic2.y2]) ln.priority = t.xmintic2.priority ln.x = xs ln.y = ys ln.viewport = [t.data.x1, t.data.x2, 0, 1] x.plot(ln, bg=bg, render=False) if l_tmp % 2 == 0: # text on txt.viewport = ln.viewport txt.x = txs txt.y = tys txt.string = ts x.plot(txt, bg=bg, render=False) # Normalizes deltas = maxs - mins data = (data - mins[:, numpy.newaxis]) / deltas[:, numpy.newaxis] # Pad attributes related to number of lines lineAtts = ["linetypes", "linewidths", "markertypes", "markersizes"] if self.markercolors is not None: lineAtts.append("markercolors") if self.linecolors is not None: lineAtts.append("linecolors") for att in lineAtts: # prepare local lists exec("%s = list(self.%s)" % (att, att)) exec("while len(%s) < nlines: %s+=[%s[-1]]" % (att, att, att)) if self.linecolors is None: linecolors = vcs.getcolors(list(range(nlines + 1))) if self.markercolors is None: markercolors = vcs.getcolors(list(range(nlines + 1))) # Mark fully missing models scratched = [] for i in range(nlines): if data[:, i].count() > 0: scratched.append(False) else: scratched.append(True) # Now draws the legend t.drawLinesAndMarkersLegend( x, linecolors, linetypes, linewidths, # noqa markercolors, markertypes, markersizes, # noqa [str(v) for v in array.getAxis(-1)], bg=bg, render=False, scratched=scratched) lst = ["max", "min", "mean"] t.blank(lst) t.drawAttributes(x, array, self, bg=bg) t.blank() t.data.priority = 1 for i in range(nlines): if data[:, i].count() > 0: ln_tmp = vcs.create1d() ln_tmp.colormap = self.colormap ln_tmp.linecolor = linecolors[i] ln_tmp.linewidth = linewidths[i] # noqa ln_tmp.linetype = linetypes[i] # noqa ln_tmp.marker = markertypes[i] # noqa ln_tmp.markercolor = markercolors[i] ln_tmp.markersize = markersizes[i] # noqa ln_tmp.datawc_y1 = 0. ln_tmp.datawc_y2 = 1. if i < nlines - 1: x.plot(data[:, i], t, ln_tmp, bg=bg, render=False) else: x.plot(data[:, i], t, ln_tmp, bg=bg, render=render)
def generateTemplate(self): template = vcs.createtemplate() # Now sets all the things for the template... # Sets a bunch of template attributes to off for att in [ 'line1', 'line2', 'line3', 'line4', 'box2', 'box3', 'box4', 'min', 'max', 'mean', 'xtic1', 'xtic2', 'ytic1', 'ytic2', 'xvalue', 'yvalue', 'zvalue', 'tvalue', 'xunits', 'yunits', 'zunits', 'tunits', 'source', 'title', 'dataname', ]: a = getattr(template, att) setattr(a, 'priority', 0) for att in [ 'xname', 'yname', ]: a = getattr(template, att) setattr(a, 'priority', 0) template.data.x1 = self.PLOT_SETTINGS.x1 template.data.x2 = self.PLOT_SETTINGS.x2 template.data.y1 = self.PLOT_SETTINGS.y1 template.data.y2 = self.PLOT_SETTINGS.y2 template.box1.x1 = self.PLOT_SETTINGS.x1 template.box1.x2 = self.PLOT_SETTINGS.x2 template.box1.y1 = self.PLOT_SETTINGS.y1 template.box1.y2 = self.PLOT_SETTINGS.y2 template.xname.y = self.PLOT_SETTINGS.y2 + .02 template.yname.x = self.PLOT_SETTINGS.x2 + .01 template.xlabel1.y = self.PLOT_SETTINGS.y1 template.xlabel2.y = self.PLOT_SETTINGS.y2 template.xlabel1.texttable = self.PLOT_SETTINGS.tictable template.xlabel2.texttable = self.PLOT_SETTINGS.tictable template.xlabel1.textorientation = \ self.PLOT_SETTINGS.xticorientation template.xlabel2.textorientation = \ self.PLOT_SETTINGS.xticorientation template.ylabel1.x = self.PLOT_SETTINGS.x1 template.ylabel2.x = self.PLOT_SETTINGS.x2 template.ylabel1.texttable = self.PLOT_SETTINGS.tictable template.ylabel2.texttable = self.PLOT_SETTINGS.tictable template.ylabel1.textorientation = \ self.PLOT_SETTINGS.yticorientation template.ylabel2.textorientation = \ self.PLOT_SETTINGS.yticorientation if self.PLOT_SETTINGS.xtic1.y1 is not None: template.xtic1.y1 = self.PLOT_SETTINGS.xtic1.y1 template.xtic1.priority = 1 if self.PLOT_SETTINGS.xtic1.y2 is not None: template.xtic1.y2 = self.PLOT_SETTINGS.xtic1.y2 template.xtic1.priority = 1 if self.PLOT_SETTINGS.xtic2.y1 is not None: template.xtic2.y1 = self.PLOT_SETTINGS.xtic2.y1 template.xtic2.priority = 1 if self.PLOT_SETTINGS.xtic2.y2 is not None: template.xtic2.y2 = self.PLOT_SETTINGS.xtic2.y2 template.xtic2.priority = 1 if self.PLOT_SETTINGS.ytic1.x1 is not None: template.ytic1.x1 = self.PLOT_SETTINGS.ytic1.x1 template.ytic1.priority = 1 if self.PLOT_SETTINGS.ytic1.x2 is not None: template.ytic1.x2 = self.PLOT_SETTINGS.ytic1.x2 template.ytic1.priority = 1 if self.PLOT_SETTINGS.ytic2.x1 is not None: template.ytic2.priority = 1 template.ytic2.x1 = self.PLOT_SETTINGS.ytic2.x1 if self.PLOT_SETTINGS.ytic2.x2 is not None: template.ytic2.priority = 1 template.ytic2.x2 = self.PLOT_SETTINGS.ytic2.x2 template.legend.x1 = self.PLOT_SETTINGS.legend.x1 template.legend.x2 = self.PLOT_SETTINGS.legend.x2 template.legend.y1 = self.PLOT_SETTINGS.legend.y1 template.legend.y2 = self.PLOT_SETTINGS.legend.y2 try: tmp = vcs.createtextorientation('crap22') except Exception: tmp = vcs.gettextorientation('crap22') tmp.height = 12 # tmp.halign = 'center' # template.legend.texttable = tmp template.legend.textorientation = tmp return template
def overlay_png(canvas, png_path, data, data2=None, gm=None, scale=.75, template=None, continents=1, legend_bg_color=None): canvas.open() canvas.put_png_on_canvas(png_path, zoom=scale) canvas.clear() canvas.put_png_on_canvas(png_path, zoom=scale) is_portrait = canvas.size < 1 if template: t = vcs.createtemplate(template) else: t = vcs.createtemplate() padding = (1 - scale) / 2. # Plot & outline t.data.priority = 10 t.data.x1 = padding t.data.x2 = 1 - padding t.data.y1 = padding t.data.y2 = 1 - padding t.box1.x1 = padding t.box1.x2 = 1 - padding t.box1.y1 = padding t.box1.y2 = 1 - padding # Ticks ticlen = abs(t.xtic1.y2 - t.xtic1.y1) t.xtic1.y1 = padding t.xtic1.y2 = padding - ticlen t.ytic1.x1 = padding t.ytic1.x2 = padding - ticlen / 2. t.xtic2.y1 = 1 - padding t.xtic2.y2 = 1 - (padding - ticlen / 2.) t.ytic2.x1 = 1 - padding t.ytic2.x2 = 1 - (padding - ticlen / 2.) # Tick Labels t.xlabel1.y = t.xtic1.y2 - ticlen t.xlabel2.y = t.xtic2.y2 + ticlen t.ylabel1.x = t.ytic1.x2 - ticlen / 2. t.ylabel2.x = t.ytic2.x2 + ticlen / 2. # Axis labels t.xname.y = t.xlabel1.y - ticlen * 2 t.yname.x = t.ylabel1.x - ticlen * 2 # Legend if is_portrait: t.legend.x1 = t.data.x1 t.legend.x2 = t.data.x2 t.legend.y1 = t.data.y1 / 4. t.legend.y2 = t.legend.y1 + padding / 3. else: t.legend.x1 = t.data.x2 + padding / 4. t.legend.x2 = t.legend.x1 + padding / 4. t.legend.y1 = t.data.y1 t.legend.y2 = t.data.y2 # Legend's bg if legend_bg_color is not None: bg_boxes = canvas.createfillarea("bg") bg_boxes.x = [t.legend.x1,t.legend.x1,t.legend.x2,t.legend.x2] bg_boxes.y = [t.legend.y1,t.legend.y2,t.legend.y2,t.legend.y1] bg_boxes.color = [legend_bg_color] canvas.plot(bg_boxes) plot_args = [data, data2, t, gm] kwargs = {"continents": continents} return canvas.plot(*[p for p in plot_args if p is not None], **kwargs)
def get_templates(): """ Retrieve and customize all templates used in the visualization """ tmpl_0 = vcs.createtemplate() tmpl_0.ytic1.x2 = 0.075 tmpl_0.ytic1.line = 'std' tmpl_0.ytic1.x1 = 0.0705 tmpl_0.ytic2.x2 = 0.5295 tmpl_0.ytic2.line = 'std' tmpl_0.ytic2.x1 = 0.525 tmpl_0.logicalmask.priority = 0 tmpl_0.dataname.priority = 0 tmpl_0.xunits.priority = 0 tmpl_0.data.x1 = 0.075 tmpl_0.data.x2 = 0.525 tmpl_0.data.y1 = 0.707061 tmpl_0.data.y2 = 0.932061 tmpl_0.ymintic2.priority = 0 tmpl_0.xlabel2.priority = 0 tmpl_0.box2.priority = 0 tmpl_0.comment2.priority = 0 tmpl_0.function.priority = 0 tmpl_0.xtic2.y1 = 0.932061 tmpl_0.xtic2.line = 'std' tmpl_0.xtic2.y2 = 0.938361 tmpl_0.crtime.priority = 0 tmpl_0.zname.priority = 0 tmpl_0.units.priority = 0 tmpl_0.box4.priority = 0 tmpl_0.box3.priority = 0 tmpl_0.xmintic1.priority = 0 tmpl_0.xmintic2.priority = 0 tmpl_0.zvalue.priority = 0 tmpl_0.transformation.priority = 0 tmpl_0.yvalue.priority = 0 tmpl_0.mean.priority = 0 tmpl_0.ymintic1.priority = 0 tmpl_0.xtic1.y1 = 0.699861 tmpl_0.xtic1.line = 'std' tmpl_0.xtic1.y2 = 0.707061 tmpl_0.xlabel1.textorientation = 'center10' tmpl_0.xlabel1.y = 0.697 tmpl_0.xlabel1.texttable = 'font3' tmpl_0.box1.x1 = 0.075 tmpl_0.box1.x2 = 0.525 tmpl_0.box1.y1 = 0.707061 tmpl_0.box1.line = 'std' tmpl_0.box1.y2 = 0.932061 tmpl_0.zunits.priority = 0 tmpl_0.file.priority = 0 tmpl_0.tunits.priority = 0 tmpl_0.line4.priority = 0 tmpl_0.line3.priority = 0 tmpl_0.line2.priority = 0 tmpl_0.line1.priority = 0 tmpl_0.max.priority = 0 tmpl_0.tname.priority = 0 tmpl_0.xname.priority = 0 tmpl_0.xvalue.priority = 0 tmpl_0.crdate.priority = 0 tmpl_0.tvalue.priority = 0 tmpl_0.ylabel1.textorientation = 'right10' tmpl_0.ylabel1.x = 0.068 tmpl_0.ylabel1.texttable = 'font3' tmpl_0.yname.priority = 0 tmpl_0.ylabel2.priority = 0 tmpl_0.yunits.priority = 0 tmpl_0.comment4.priority = 0 tmpl_0.min.priority = 0 tmpl_0.comment1.textorientation = 'center20' tmpl_0.comment1.y = 0.970061 tmpl_0.comment1.x = 0.30242 tmpl_0.comment1.texttable = 'font3' tmpl_0.comment3.priority = 0 tmpl_0.title.textorientation = 'left15' tmpl_0.title.y = 0.809506 tmpl_0.title.x = 0.552 tmpl_0.title.texttable = 'font3' tmpl_0.legend.y1 = 0.66 tmpl_0.legend.y2 = 0.675 tmpl_0.legend.line = 'std' tmpl_0.legend.textorientation = 'center10' tmpl_0.legend.x2 = 0.525 tmpl_0.legend.texttable = 'font3' tmpl_0.legend.x1 = 0.075 tmpl_1 = vcs.createtemplate() tmpl_1.ytic1.x2 = 0.075 tmpl_1.ytic1.line = 'std' tmpl_1.ytic1.x1 = 0.0705 tmpl_1.ytic2.x2 = 0.5295 tmpl_1.ytic2.line = 'std' tmpl_1.ytic2.x1 = 0.525 tmpl_1.logicalmask.priority = 0 tmpl_1.dataname.priority = 0 tmpl_1.xunits.priority = 0 tmpl_1.data.x1 = 0.075 tmpl_1.data.x2 = 0.525 tmpl_1.data.y1 = 0.3915 tmpl_1.data.y2 = 0.6165 tmpl_1.ymintic2.priority = 0 tmpl_1.xlabel2.priority = 0 tmpl_1.box2.priority = 0 tmpl_1.comment2.priority = 0 tmpl_1.function.priority = 0 tmpl_1.xtic2.y1 = 0.6165 tmpl_1.xtic2.line = 'std' tmpl_1.xtic2.y2 = 0.6228 tmpl_1.crtime.priority = 0 tmpl_1.zname.priority = 0 tmpl_1.units.priority = 0 tmpl_1.box4.priority = 0 tmpl_1.box3.priority = 0 tmpl_1.xmintic1.priority = 0 tmpl_1.xmintic2.priority = 0 tmpl_1.zvalue.priority = 0 tmpl_1.transformation.priority = 0 tmpl_1.yvalue.priority = 0 tmpl_1.mean.priority = 0 tmpl_1.ymintic1.priority = 0 tmpl_1.xtic1.y1 = 0.3843 tmpl_1.xtic1.line = 'std' tmpl_1.xtic1.y2 = 0.3915 tmpl_1.xlabel1.textorientation = 'center10' tmpl_1.xlabel1.y = 0.382 tmpl_1.xlabel1.texttable = 'font3' tmpl_1.box1.x1 = 0.075 tmpl_1.box1.x2 = 0.525 tmpl_1.box1.y1 = 0.3915 tmpl_1.box1.line = 'std' tmpl_1.box1.y2 = 0.6165 tmpl_1.zunits.priority = 0 tmpl_1.file.priority = 0 tmpl_1.tunits.priority = 0 tmpl_1.line4.priority = 0 tmpl_1.line3.priority = 0 tmpl_1.line2.priority = 0 tmpl_1.line1.priority = 0 tmpl_1.max.priority = 0 tmpl_1.tname.priority = 0 tmpl_1.xname.priority = 0 tmpl_1.xvalue.priority = 0 tmpl_1.crdate.priority = 0 tmpl_1.tvalue.priority = 0 tmpl_1.ylabel1.textorientation = 'right10' tmpl_1.ylabel1.x = 0.068 tmpl_1.ylabel1.texttable = 'font3' tmpl_1.yname.priority = 0 tmpl_1.ylabel2.priority = 0 tmpl_1.yunits.priority = 0 tmpl_1.comment4.priority = 0 tmpl_1.min.priority = 0 tmpl_1.comment1.priority = 0 tmpl_1.comment3.priority = 0 tmpl_1.title.textorientation = 'left15' tmpl_1.title.y = 0.494445 tmpl_1.title.x = 0.552 tmpl_1.title.texttable = 'font3' tmpl_1.legend.y1 = 0.341909 tmpl_1.legend.y2 = 0.358555 tmpl_1.legend.line = 'std' tmpl_1.legend.textorientation = 'center10' tmpl_1.legend.x2 = 0.523449 tmpl_1.legend.texttable = 'font3' tmpl_1.legend.x1 = 0.0726107 tmpl_2 = vcs.createtemplate() tmpl_2.ytic1.x2 = 0.075 tmpl_2.ytic1.line = 'std' tmpl_2.ytic1.x1 = 0.0705 tmpl_2.ytic2.x2 = 0.5295 tmpl_2.ytic2.line = 'std' tmpl_2.ytic2.x1 = 0.525 tmpl_2.logicalmask.priority = 0 tmpl_2.dataname.priority = 0 tmpl_2.xunits.priority = 0 tmpl_2.data.x1 = 0.075 tmpl_2.data.x2 = 0.525 tmpl_2.data.y1 = 0.0685 tmpl_2.data.y2 = 0.2935 tmpl_2.ymintic2.priority = 0 tmpl_2.xlabel2.priority = 0 tmpl_2.box2.priority = 0 tmpl_2.comment2.priority = 0 tmpl_2.function.priority = 0 tmpl_2.xtic2.y1 = 0.2935 tmpl_2.xtic2.line = 'std' tmpl_2.xtic2.y2 = 0.2998 tmpl_2.crtime.priority = 0 tmpl_2.zname.priority = 0 tmpl_2.units.priority = 0 tmpl_2.box4.priority = 0 tmpl_2.box3.priority = 0 tmpl_2.xmintic1.priority = 0 tmpl_2.xmintic2.priority = 0 tmpl_2.zvalue.priority = 0 tmpl_2.transformation.priority = 0 tmpl_2.yvalue.priority = 0 tmpl_2.mean.priority = 0 tmpl_2.ymintic1.priority = 0 tmpl_2.xtic1.y1 = 0.0622 tmpl_2.xtic1.line = 'std' tmpl_2.xtic1.y2 = 0.0682 tmpl_2.xlabel1.textorientation = 'center10' tmpl_2.xlabel1.y = 0.06 tmpl_2.xlabel1.texttable = 'font3' tmpl_2.box1.x1 = 0.075 tmpl_2.box1.x2 = 0.525 tmpl_2.box1.y1 = 0.0685 tmpl_2.box1.line = 'std' tmpl_2.box1.y2 = 0.2935 tmpl_2.zunits.priority = 0 tmpl_2.file.priority = 0 tmpl_2.tunits.priority = 0 tmpl_2.line4.priority = 0 tmpl_2.line3.priority = 0 tmpl_2.line2.priority = 0 tmpl_2.line1.priority = 0 tmpl_2.max.priority = 0 tmpl_2.tname.priority = 0 tmpl_2.xname.priority = 0 tmpl_2.xvalue.priority = 0 tmpl_2.crdate.priority = 0 tmpl_2.tvalue.priority = 0 tmpl_2.ylabel1.textorientation = 'right10' tmpl_2.ylabel1.x = 0.068 tmpl_2.ylabel1.texttable = 'font3' tmpl_2.yname.priority = 0 tmpl_2.ylabel2.priority = 0 tmpl_2.yunits.priority = 0 tmpl_2.comment4.priority = 0 tmpl_2.min.priority = 0 tmpl_2.comment1.priority = 0 tmpl_2.comment3.priority = 0 tmpl_2.title.textorientation = 'left15' tmpl_2.title.y = 0.169792 tmpl_2.title.x = 0.552 tmpl_2.title.texttable = 'font3' tmpl_2.legend.y1 = 0.025 tmpl_2.legend.y2 = 0.04 tmpl_2.legend.line = 'std' tmpl_2.legend.textorientation = 'center10' tmpl_2.legend.x2 = 0.525 tmpl_2.legend.texttable = 'font3' tmpl_2.legend.x1 = 0.075 return tmpl_0, tmpl_1, tmpl_2
def spaghetti_plot(variables, template=None, min_y=None, max_y=None, left_label=None, right_label=None, tick_sides=None, line="default", marker="default", x_labels="*", y_labels="*", canvas=None): """ This file is ready to be imported by your scripts, and you can just call this function. Sample usage is below. variables: List of variables to plot template: The template to use as the base for the plot. min_y: If you want to adjust the y axis bounds, you can set a minimum value. Will be derived from data if not specified. max_y: If you want to adjust the y axis bounds, you can set a maximum value. Will be derived from data if not specified. left_label: Text to put on the left Y axis right_label: Text to put on the right Y axis tick_sides: A list of "left" or "right" values indicating which side of the chart you want the variable axes to be displayed. line: A line object or name of a line object used to describe the lines plotted. Set to None to hide. marker: A marker object or name of a marker object used to describe the markers plotted. Set to None to hide. x_labels: Dictionary for setting axis tick labels y_labels: Dictionary for setting axis tick labels """ if canvas is None: canvas = vcs.init() if isinstance(template, (str, unicode)): template = vcs.gettemplate(template) if template is None: # Use our custom default template for 1ds template = vcs.createtemplate() # Shrink the template a bit template.scale(.78, "x") template.move(.02, "x") template.yname.x = .01 template.data.y1 = .1 template.box1.y1 = .1 ticlen = template.xtic1.y2 - template.xtic1.y1 template.xtic1.y1 = template.data.y1 template.xtic1.y2 = template.xtic1.y1 + ticlen template.xtic2.priority = 0 template.xlabel1.y = template.xtic1.y2 - .01 template.legend.x1 = template.data.x2 + (1 - template.data.x2) / 3. template.legend.x2 = .95 template.legend.y1 = template.data.y1 template.legend.y2 = template.data.y2 template.yname.y = (template.data.y1 + template.data.y2)/2. template.xname.y = template.xlabel1.y - .05 # The labels don't make any sense with multiple values; hide them. template.min.priority = 0 template.max.priority = 0 template.mean.priority = 0 template.dataname.priority = 0 templates = EzTemplate.oneD(len(variables), template=template) templates.x = canvas if tick_sides is None: tick_sides = ["left"] * len(variables) clean_ticks = [] for t in tick_sides: if t.lower() not in ('left', 'right'): raise ValueError("tick_sides must be a list of 'left' or 'right' values; found '%s'." % t) clean_ticks.append(t.lower()) tick_sides = clean_ticks if len(tick_sides) < len(variables): tick_sides += tick_sides[-1:] * len(variables) # Store min/max per side for appropriate scaling min_vals = {"left": min_y, "right": min_y} if min_y is None: for i, var in enumerate(variables): v_min = min(var) min_y = min_vals[tick_sides[i]] if min_y is None or min_y > v_min: min_vals[tick_sides[i]] = v_min max_vals = {"left": max_y, "right": max_y} if max_y is None: for i, var in enumerate(variables): v_max = max(var) max_y = max_vals[tick_sides[i]] if max_y is None or max_y < v_max: max_vals[tick_sides[i]] = v_max if isinstance(line, (str, unicode)): line = vcs.getline(line) if isinstance(marker, (str, unicode)): marker = vcs.getmarker(marker) to_pad = [] if line is not None: widths = line.width to_pad.append(widths) styles = line.type to_pad.append(styles) colors = line.color to_pad.append(colors) if marker is not None: markers = marker.type to_pad.append(markers) marker_colors = marker.color to_pad.append(marker_colors) marker_sizes = marker.size to_pad.append(marker_sizes) for padded in to_pad: if len(padded) < len(variables): padded += padded[-1:] * (len(variables) - len(padded)) for n in range(len(variables)): gm = vcs.create1d() if line is not None: gm.line = styles[n] gm.linewidth = widths[n] gm.linecolor = colors[n] else: gm.linewidth = 0 if marker is not None: gm.marker = markers[n] gm.markersize = marker_sizes[n] gm.markercolor = marker_colors[n] else: gm.marker = None gm.datawc_y1 = min_vals[tick_sides[n]] gm.datawc_y2 = max_vals[tick_sides[n]] template = templates.get(n) gm.xticlabels1 = x_labels if tick_sides[n] == "left": if tick_sides.index("left") == n: template.ylabel1.priority = 1 if left_label is not None: template.yname.priority = 0 left_text = vcs.createtext(Tt_source=template.yname.texttable, To_source=template.yname.textorientation) left_text.x = template.yname.x left_text.y = template.yname.y left_text.string = [left_label] templates.x.plot(left_text) else: template.ylabel1.priority = 0 template.yname.priority = 0 template.ylabel2.priority = 0 gm.yticlabels1 = y_labels gm.yticlabels2 = "" else: template.ylabel1.priority = 0 if tick_sides.index("right") == n: template.ylabel2.priority = 1 if right_label is not None: right_text = vcs.createtext(Tt_source=template.yname.texttable, To_source=template.yname.textorientation) right_text.x = template.data.x2 + (template.data.x1 - template.yname.x) right_text.y = template.yname.y right_text.string = [right_label] templates.x.plot(right_text) else: template.ylabel2.priority = 0 gm.yticlabels1 = "" gm.yticlabels2 = y_labels if n != 0: template.xlabel1.priority = 0 template.xname.priority = 0 var = variables[n] templates.x.plot(var, gm, template) return templates.x
import vcs, cdms2 f = cdms2.open(vcs.sample_data + '/clt.nc') s = f("clt", squeeze=1, time="1979-1") zeroed = cdms2.createVariable([[0 for _ in range(s.shape[1])] for _ in range(s.shape[0])], axes=s.getAxisList(), grid=s.getGrid()) x = vcs.init() box = vcs.createboxfill() box.boxfill_type = "custom" box.levels = [1, 100] box.fillareacolors = [242] light = vcs.createline() colormap = vcs.createcolormap() colormap.index[1] = [10, 10, 10] light.colormap = colormap light.type = "dash-dot" dark = vcs.createline() dark.width = 2 justdata = vcs.createtemplate() justdata.blank() justdata.data.priority = 1 x.plot(s, continents=4, continents_line=light, bg=1) x.plot(zeroed, justdata, box, continents=1, continents_line=dark, bg=1) x.png("nice_continents")
labels = numpy.round(labels, 0) labels = list(labels) labels[0] = 0 nice_labels = [] for i in range(len(labels)): val = int(labels[i]) if val >= 1000: val = val / 1000 val = "%dk" % val nice_labels.append(str(val)) oned.yticlabels1 = {s: l for s, l in zip(scale, nice_labels)} oned.linewidth = 2 t = vcs.createtemplate() t.blank() t.data.priority = 1 t.data.x1 = .1 t.data.x2 = .9 t.box1.priority = 1 t.box1.x1 = .1 t.box1.x2 = .9 t.ytic1.priority = 1 t.ytic1.x1 = .1 t.ytic1.x2 = .09 t.ylabel1.x = .09 t.ylabel1.priority = 1 t.xlabel1.priority = 1 t.xtic1.priority = 1
# Initialize canvas: canvas = vcs.init() canvas.setantialiasing(0) canvas.setbgoutputdimensions(1200, 1091, units="pixels") canvas.drawlogooff() # Create and plot quick boxfill with default settings: boxfill = canvas.createboxfill() # Change the type boxfill.boxfill_type = 'custom' # Set levels to ignore 0 boxfill.levels = [1, 100] # Pick a color, any color boxfill.fillareacolors = [242] dataonly = vcs.createtemplate() dataonly.blank() dataonly.data.priority = 1 multitemplate = EzTemplate.Multi(template=dataonly, rows=4, columns=3) line_styles = ['long-dash', 'dot', 'dash', 'dash-dot', 'solid'] for i in range(12): cont_index = i % 6 + 1 cont_line = vcs.createline() cont_line.width = i % 3 + 1 cont_line.type = line_styles[i % 5] cont_line.color = i + 200 template = multitemplate.get(i) canvas.plot(clt, template, boxfill, continents=cont_index, continents_line=cont_line, bg=1)
def init_polar(): # Create nice polar template try: t = vcs.createtemplate("polar_oned") t.data.x1 = .2 t.data.x2 = .8 t.data.y1 = .2 t.data.y2 = .8 t.legend.x1 = .85 t.legend.x2 = 1 t.legend.y1 = .15 t.legend.y2 = .85 dash = vcs.createline() dash.type = "dash" dot = vcs.createline() dot.type = "dot" t.xtic1.line = dash t.ytic1.line = dot left_aligned = vcs.createtextorientation() left_aligned.halign = "left" left_aligned.valign = "half" t.legend.textorientation = left_aligned except vcs.vcsError: # Template already exists pass # Create some nice default polar GMs degree_polar = polar.Gpo("degrees", template="polar_oned") degree_polar.datawc_x1 = 0 degree_polar.datawc_x2 = 360 degree_polar.xticlabels1 = { i: str(i) for i in range(0, 360, 45) } clock_24 = polar.Gpo("diurnal", template="polar_oned") clock_24.datawc_x1 = 0 clock_24.datawc_x2 = 24 clock_24.clockwise = True # 6 AM on the right clock_24.theta_offset = -6 clock_24.xticlabels1 = { i: str(i) for i in range(0, 24, 3) } clock_24_meridiem = polar.Gpo("diurnal_12_hour", source="diurnal", template="polar_oned") clock_24_meridiem.xticlabels1 = { 0: "12 AM", 3: "3 AM", 6: "6 AM", 9: "9 AM", 12: "12 PM", 15: "3 PM", 18: "6 PM", 21: "9 PM" } clock_12 = polar.Gpo("semidiurnal", source="diurnal", template="polar_oned") clock_12.datawc_x2 = 12 clock_12.xticlabels1 = { i: str(i) for i in range(3, 13, 3) } # 3 on the right clock_12.theta_offset = -3 annual_cycle = polar.Gpo("annual_cycle", template="polar_oned") annual_cycle.datawc_x1 = 1 annual_cycle.datawc_x2 = 13 annual_cycle.clockwise = True annual_cycle.xticlabels1 = { 1: "Jan", 2: "Feb", 3: "Mar", 4: "Apr", 5: "May", 6: "Jun", 7: "Jul", 8: "Aug", 9: "Sep", 10: "Oct", 11: "Nov", 12: "Dec" } # Put December on the top annual_cycle.theta_offset = -2 seasonal = polar.Gpo("seasonal", template="polar_oned") seasonal.datawc_x1 = 0 seasonal.datawc_x2 = 4 seasonal.xticlabels1 = {0: "DJF", 1: "MAM", 2: "JJA", 3: "SON"} seasonal.clockwise = True # DJF on top seasonal.theta_offset = -1
import os, sys, cdms2, vcs, testing.regression as regression # Load the clt data: dataFile = cdms2.open(os.path.join(vcs.sample_data, "clt.nc")) clt = dataFile("clt") clt = clt(latitude=(-90.0, 90.0), longitude=(-180., 175.), squeeze=1, time=('1979-1-1 0:0:0.0', '1988-12-1 0:0:0.0')) # Initialize canvas: canvas = regression.init() t1 = vcs.createtemplate() t1.scale(.5, "y") t1.move(-.15, "y") t2 = vcs.createtemplate(source=t1.name) t2.move(.5, 'y') canvas.plot(clt, t1, continents=0, bg=True) canvas.plot(clt, t2, continents=1, bg=True) regression.run(canvas, "test_vcs_no_continents.png")
def init_polar(): # Create nice polar template try: t = vcs.createtemplate("polar_oned") t.data.x1 = .2 t.data.x2 = .8 t.data.y1 = .2 t.data.y2 = .8 t.legend.x1 = .85 t.legend.x2 = 1 t.legend.y1 = .15 t.legend.y2 = .85 dash = vcs.createline() dash.type = "dash" dot = vcs.createline() dot.type = "dot" t.xtic1.line = dash t.ytic1.line = dot left_aligned = vcs.createtextorientation() left_aligned.halign = "left" left_aligned.valign = "half" t.legend.textorientation = left_aligned except vcs.vcsError: # Template already exists pass # Create some nice default polar GMs degree_polar = Gpo("degrees", template="polar_oned") degree_polar.negative_magnitude = True degree_polar.datawc_x1 = 0 degree_polar.datawc_x2 = 360 degree_polar.xticlabels1 = {i: str(i) for i in range(0, 360, 45)} clock_24 = Gpo("diurnal", template="polar_oned") clock_24.negative_magnitude = True clock_24.datawc_x1 = 0 clock_24.datawc_x2 = 24 clock_24.clockwise = True # 6 AM on the right clock_24.theta_offset = -6 clock_24.xticlabels1 = {i: str(i) for i in range(0, 24, 3)} clock_24_meridiem = Gpo("diurnal_12_hour", source="diurnal", template="polar_oned") clock_24_meridiem.xticlabels1 = { 0: "12 AM", 3: "3 AM", 6: "6 AM", 9: "9 AM", 12: "12 PM", 15: "3 PM", 18: "6 PM", 21: "9 PM" } clock_12 = Gpo("semidiurnal", source="diurnal", template="polar_oned") clock_12.negative_magnitude = True clock_12.datawc_x2 = 12 clock_12.xticlabels1 = {i: str(i) for i in range(3, 13, 3)} # 3 on the right clock_12.theta_offset = -3 annual_cycle = Gpo("annual_cycle", template="polar_oned") annual_cycle.negative_magnitude = True annual_cycle.datawc_x1 = 1 annual_cycle.datawc_x2 = 13 annual_cycle.clockwise = True annual_cycle.xticlabels1 = { 1: "Jan", 2: "Feb", 3: "Mar", 4: "Apr", 5: "May", 6: "Jun", 7: "Jul", 8: "Aug", 9: "Sep", 10: "Oct", 11: "Nov", 12: "Dec" } # Put December on the top annual_cycle.theta_offset = -2 seasonal = Gpo("seasonal", template="polar_oned") seasonal.negative_magnitude = True seasonal.datawc_x1 = 0 seasonal.datawc_x2 = 4 seasonal.xticlabels1 = {0: "DJF", 1: "MAM", 2: "JJA", 3: "SON"} seasonal.clockwise = True # DJF on top seasonal.theta_offset = -1
import vcs, os, filecmp import vcs, numpy, os, sys src = sys.argv[1] if os.path.exists("test_vcs_dump_json.json"): os.remove("test_vcs_dump_json.json") b = vcs.createboxfill("Charles.Doutriaux") b.script("test_vcs_dump_json", "a") b = vcs.createisofill("Charles.Doutriaux") b.script("test_vcs_dump_json", "a") b = vcs.createisoline("Charles.Doutriaux") b.script("test_vcs_dump_json", "a") b = vcs.createmeshfill("Charles.Doutriaux") b.script("test_vcs_dump_json", "a") b = vcs.createoneD("Charles.Doutriaux") b.script("test_vcs_dump_json", "a") b = vcs.createfillarea("Charles.Doutriaux") b.script("test_vcs_dump_json", "a") b = vcs.createtext("Charles.Doutriaux") b.script("test_vcs_dump_json", "a") b = vcs.createline("Charles.Doutriaux") b.script("test_vcs_dump_json", "a") b = vcs.createmarker("Charles.Doutriaux") b.script("test_vcs_dump_json", "a") b = vcs.createtemplate("Charles.Doutriaux") b.script("test_vcs_dump_json", "a") b = vcs.createprojection("Charles.Doutriaux") b.script("test_vcs_dump_json", "a") assert (filecmp.cmp("test_vcs_dump_json.json", src))
src=sys.argv[1] if os.path.exists("test_vcs_dump_json.json"): os.remove("test_vcs_dump_json.json") b = vcs.createboxfill("Charles.Doutriaux") b.script("test_vcs_dump_json","a") b = vcs.createisofill("Charles.Doutriaux") b.script("test_vcs_dump_json","a") b = vcs.createisoline("Charles.Doutriaux") b.script("test_vcs_dump_json","a") b = vcs.createmeshfill("Charles.Doutriaux") b.script("test_vcs_dump_json","a") b = vcs.createoneD("Charles.Doutriaux") b.script("test_vcs_dump_json","a") b = vcs.createfillarea("Charles.Doutriaux") b.script("test_vcs_dump_json","a") b = vcs.createtext("Charles.Doutriaux") b.script("test_vcs_dump_json","a") b = vcs.createline("Charles.Doutriaux") b.script("test_vcs_dump_json","a") b = vcs.createmarker("Charles.Doutriaux") b.script("test_vcs_dump_json","a") b = vcs.createtemplate("Charles.Doutriaux") b.script("test_vcs_dump_json","a") b = vcs.createprojection("Charles.Doutriaux") b.script("test_vcs_dump_json","a") assert(filecmp.cmp("test_vcs_dump_json.json",src))
os.remove("test_vcs_dump_json.json") b = vcs.createboxfill("vcs_instance") b.script("test_vcs_dump_json", "a") b = vcs.createisofill("vcs_instance") b.script("test_vcs_dump_json", "a") b = vcs.createisoline("vcs_instance") b.script("test_vcs_dump_json", "a") b = vcs.createmeshfill("vcs_instance") b.script("test_vcs_dump_json", "a") b = vcs.create1d("vcs_instance") b.script("test_vcs_dump_json", "a") b = vcs.createfillarea("vcs_instance") b.script("test_vcs_dump_json", "a") b = vcs.createvector("vcs_instance") b.script("test_vcs_dump_json", "a") b = vcs.createtext("vcs_instance") b.script("test_vcs_dump_json", "a") b = vcs.createline("vcs_instance") b.script("test_vcs_dump_json", "a") b = vcs.createmarker("vcs_instance") b.script("test_vcs_dump_json", "a") b = vcs.createtemplate("vcs_instance") b.script("test_vcs_dump_json", "a") b = vcs.createprojection("vcs_instance") b.script("test_vcs_dump_json", "a") print "Comparing:", os.path.realpath("test_vcs_dump_json.json"), src assert (filecmp.cmp("test_vcs_dump_json.json", src)) os.remove("test_vcs_dump_json.json")