def applyAttributesFromVCStmpl(tmpl,tmplattribute,txtobj=None): tatt = getattr(tmpl,tmplattribute) if txtobj is None: txtobj = vcs.createtext(To_source=tatt.textorientation,Tt_source=tatt.texttable) for att in ["x","y","priority"]: setattr(txtobj,att,getattr(tatt,att)) return txtobj
def setTextObject(self, textobject): self.textobj = textobject tmpobj = vcs.createtext(Tt_source=self.textobj.Tt, To_source=self.textobj.To) tmpobj.string = ["%s Preview" % self.textobj.name] tmpobj.x = [.5] tmpobj.y = [.5] self.clear() self.plot(tmpobj)
def __init__(self, show=False, array=None, lightcolor="white", darkcolor="black", format="{0:.2f}"): self.show = show self.array = array self.text = vcs.createtext() self.text.valign = "half" self.text.halign = "center" self.lightcolor = lightcolor self.darkcolor = darkcolor self.format = format
def test_preview(): prev = TextStylePreview.TextStylePreviewWidget() text = vcs.createtext() text.name = "test" prev.setTextObject(text) assert prev.textobj == text text.name = "pizza" prev.update() assert prev.textobj.name == "pizza"
def editors(): edit1 = TextStyleEditorWidget() t = vcs.createtext() t.name = "header" edit1.setTextObject(t) edit2 = TextStyleEditorWidget() t = vcs.createtext() t.name = "header" t.valign = 0 t.halign = 1 edit2.setTextObject(t) edit3 = TextStyleEditorWidget() t = vcs.createtext() t.name = "header" t.valign = 4 t.halign = 2 edit3.setTextObject(t) return edit1, edit2, edit3
def editors(): edit1 = TextStyleEditor.TextStyleEditorWidget() t = vcs.createtext() t.name = "header" edit1.setTextObject(t) edit2 = TextStyleEditor.TextStyleEditorWidget() t = vcs.createtext() t.name = "header" t.valign = 0 t.halign = 1 edit2.setTextObject(t) edit3 = TextStyleEditor.TextStyleEditorWidget() t = vcs.createtext() t.name = "header" t.valign = 4 t.halign = 2 edit3.setTextObject(t) return edit1, edit2, edit3
def __init__(self): self.x1 = .12 self.x2 = .84 self.y1 = .17 self.y2 = .8 self.levels = None self.colormap = None self.fillareacolors = None self.legend = XYs(.89, .91, self.y1, self.y2) # X ticks self.xticorientation = vcs.createtextorientation() self.xticorientation.angle = 360 - 90 self.xticorientation.halign = 'right' self.xticorientation.height = 10 # Y ticks self.yticorientation = vcs.createtextorientation() self.yticorientation.angle = 0 self.yticorientation.halign = 'right' self.yticorientation.height = 10 # Ticks table self.tictable = vcs.createtexttable() # parameters text settings self.parameterorientation = vcs.createtextorientation() self.parameterorientation.angle = 0 self.parameterorientation.halign = 'center' self.parameterorientation.height = 20 self.parametertable = vcs.createtexttable() # values in cell setting self.values = Values() # Defaults self.draw_mesh = 'y' self.missing_color = 3 self.xtic1 = Ys(None, None) self.xtic2 = Ys(None, None) self.ytic1 = Xs(None, None) self.ytic2 = Xs(None, None) # Set the logo textorientation self.logo = None # Set the time stamp time_stamp = vcs.createtext() time_stamp.height = 10 time_stamp.halign = 'center' time_stamp.path = 'right' time_stamp.valign = 'half' time_stamp.x = [0.9] time_stamp.y = [0.96] self.time_stamp = time_stamp
def text(string, x=.5, y=.5, halign="center", valign="half", height=10, color="black"): # First plot coordinate of canvas txt = vcs.createtext() txt.string = string txt.halign = halign txt.valign = valign txt.x = x txt.y = y txt.height = height txt.color = color txt.priority = 2 # To ensure it shows on top of fillarea and line objects canvas.plot(txt)
def axisToPngCoords(values, gm, template, axis='x1', worldCoordinates=[0, 360, -90, 90], png=None, geometry=None): """ Given a set of axis values/labels, a graphic method and a template, maps each label to an area on pmg Warning does not handle projections yet. :Example: .. doctest:: utils_axisToPngCoords >>> a=vcs.init(bg=True) >>> box=vcs.createboxfill() >>> array=[range(10) for _ in range(10)] >>> a.plot(box,array) # plot something on canvas <vcs.displayplot.Dp ...> >>> a.png('box.png', width=1536, height=1186) # make a png >>> fnm = cdat_info.get_sampledata_path()+"/clt.nc" >>> f=cdms2.open(fnm) >>> clt=f("clt",time=slice(0,1),squeeze=1) >>> box = vcs.createboxfill() >>> template = vcs.createtemplate() >>> areas = axisToPngCoords(clt.getLongitude(), box, template) """ if png is None and geometry is None: x = vcs.init() x.open() ci = x.canvasinfo() x.close() del (x) pwidth = width = ci["width"] pheight = height = ci["height"] if png is not None: pwidth, pheight = getPngDimensions(png) if geometry is None: width, height = pwidth, pheight if geometry is not None: width, height = geometry if isinstance(template, str): template = vcs.gettemplate(template) x = vcs.init(geometry=(width, height), bg=True) # x/y ratio to original png xRatio = float(width) / pwidth yRatio = float(height) / pheight # Prepare dictionary of values, labels pairs mapped = [] direction = axis[0] if direction == "x": other_direction = "y" c1 = int(width * template.data.x1 * xRatio) c2 = int(width * template.data.x2 * xRatio) else: other_direction = "x" c1 = int(height * template.data.y1 * yRatio) c2 = int(height * template.data.y2 * yRatio) location = axis[-1] datawc1 = getattr(gm, "datawc_{}1".format(direction)) if datawc1 == 1.e20: start = values[0] end = values[-1] else: start = datawc1 end = getattr(gm, "datawc_{}2".format(direction)) label = getattr(template, "{}label{}".format(direction, location)) Tt_source = label.texttable To_source = label.textorientation text = vcs.createtext(Tt_source=Tt_source, To_source=To_source) setattr(text, other_direction, getattr(label, other_direction)) if direction == "x": text.worldcoordinate = [start, end, 0, 1] else: text.worldcoordinate = [0, 1, start, end] ticlabels = getattr(gm, "{}ticlabels{}".format(direction, location)) if ticlabels == "*": lbls = vcs.mklabels(vcs.mkscale(start, end)) else: lbls = ticlabels # now loops thru all labels and get extents for v, l in lbls.items(): if start <= v and v <= end: text.string = str(l) setattr(text, direction, v) box = x.gettextbox(text)[0] if direction == "x": xs = worldToPixel(box[0], start, end, c1, c2).tolist() ys = [height * yRatio * (1 - c) for c in box[1]] else: xs = [width * xRatio * c for c in box[0]] ys = (height * yRatio - worldToPixel(box[1], start, end, c1, c2)).tolist() mapped.append([xs, ys]) return numpy.array(mapped)
def draw_values(self, raveled, mesh, meshfill, template): # Values to use (data or user passed) if self.PLOT_SETTINGS.values.array is None: data = MV2.array(raveled) else: data = MV2.ravel(self.PLOT_SETTINGS.values.array) if isinstance(raveled, numpy.ma.core.MaskedArray): data.mask = data.mask + raveled.mask # Now remove masked values if data.mask is not numpy.ma.nomask: # we have missing indices = numpy.argwhere(numpy.ma.logical_not(data.mask)) data = data.take(indices).filled(0)[:, 0] M = mesh.filled()[indices][:, 0] raveled = raveled.take(indices).filled(0.)[:, 0] else: M = mesh.filled() # Baricenters xcenters = numpy.average(M[:, 1], axis=-1) ycenters = numpy.average(M[:, 0], axis=-1) self.PLOT_SETTINGS.values.text.viewport = [template.data.x1, template.data.x2, template.data.y1, template.data.y2] if not numpy.allclose(meshfill.datawc_x1, 1.e20): self.PLOT_SETTINGS.values.text.worldcoordinate = [meshfill.datawc_x1, meshfill.datawc_x2, meshfill.datawc_y1, meshfill.datawc_y2] else: self.PLOT_SETTINGS.values.text.worldcoordinate = [M[:, 1].min(), M[:, 1].max(), M[:, 0].min(), M[:, 0].max()] self.PLOT_SETTINGS.values.text.string = [ self.PLOT_SETTINGS.values.format.format(value) for value in data] # Now that we have the formatted values we need get the longest string lengths = [len(txt) for txt in self.PLOT_SETTINGS.values.text.string] longest = max(lengths) index = lengths.index(longest) tmptxt = vcs.createtext() tmptxt.string = self.PLOT_SETTINGS.values.text.string[index] tmptxt.x = xcenters[index] tmptxt.y = ycenters[index] smallY = M[index, 0, :].min() bigY = M[index, 0, :].max() smallX = M[index, 1, :].min() bigX = M[index, 1, :].max() tmptxt.worldcoordinate = self.PLOT_SETTINGS.values.text.worldcoordinate tmptxt.viewport = self.PLOT_SETTINGS.values.text.viewport # Now try to shrink until it fits extent = self.x.gettextextent(tmptxt)[0] while ((extent[1] - extent[0]) / (bigX - smallX) > 1.01 or (extent[3] - extent[2]) / (bigY - smallY) > 1.01) and \ tmptxt.height >= 1: tmptxt.height -= 1 extent = self.x.gettextextent(tmptxt)[0] self.PLOT_SETTINGS.values.text.height = tmptxt.height # Finally we need to split into two text objects for dark and light background # Step 1: figure out each bin color type (dark/light) colormap = self.x.colormap if colormap is None: colormap = vcs._colorMap cmap = vcs.getcolormap(colormap) colors = meshfill.fillareacolors dark_bins = [ is_dark_color_type( *cmap.getcolorcell(color)) for color in colors] # Step 2: put values into bin (color where they land) bins = meshfill.levels[1:-1] binned = numpy.digitize(raveled, bins) isdark = [dark_bins[indx] for indx in binned] tmptxt = vcs.createtext( Tt_source=self.PLOT_SETTINGS.values.text.Tt_name, To_source=self.PLOT_SETTINGS.values.text.To_name) for pick, color in [(numpy.argwhere(isdark), self.PLOT_SETTINGS.values.lightcolor), (numpy.argwhere(numpy.logical_not(isdark)), self.PLOT_SETTINGS.values.darkcolor)]: tmptxt.x = xcenters.take(pick)[:, 0].tolist() tmptxt.y = ycenters.take(pick)[:, 0].tolist() tmptxt.string = numpy.array( self.PLOT_SETTINGS.values.text.string).take(pick)[ :, 0].tolist() tmptxt.color = color self.x.plot(tmptxt, bg=self.bg)
def get_textobject(t,att,text): obj = vcs.createtext(Tt_source=getattr(t,att).texttable,To_source=getattr(t,att).textorientation) obj.string = [text] obj.x = [getattr(t,att).x] obj.y = [getattr(t,att).y] return obj
def create_text(self, tt, to): tc = vcs.createtext(Tt_source=tt, To_source=to) self.to_cleanup.append(tc.Tt) self.to_cleanup.append(tc.To) return tc
iso = canvas.createisofill() iso.levels = [-1, -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, 0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0] iso.ext_1 = 'y' # control colorbar edge (arrow extention on/off) iso.ext_2 = 'y' # control colorbar edge (arrow extention on/off) cols = vcs.getcolors(iso.levels) iso.fillareacolors = cols iso.missing = 0 # Set missing value color as same as background # Map projection --- p = vcs.createprojection() p.type = 'robinson' iso.projection = p # Plot --- canvas.plot(eof[0],iso,template) # Title --- plot_title = vcs.createtext() plot_title.x = .5 plot_title.y = .97 plot_title.height = 23 plot_title.halign = 'center' plot_title.valign = 'top' plot_title.color='black' percentage = str(round(float(frac[0]*100.),1)) + '%' # % with one floating number plot_title.string = 'EOF first mode, HadISST('+str(start_year)+'-'+str(end_year)+'), '+percentage canvas.plot(plot_title) # Save output as image file --- canvas.png('eof_analysis.png')
templ_2.scale(.5, "y") templ_2.move(.63, "x") templ_2.move(.4, "y") templ_2.blank() templ_2.data.priority = 1 x.plot(murica, templ_2) marker2 = vcs.createmarker() marker2.type = "cross" marker2.viewport = (templ_2.data.x1, templ_2.data.x2, templ_2.data.y1, templ_2.data.y2) murica_lat = murica.getLatitude() murica_lon = murica.getLongitude() marker2.worldcoordinate = (min(murica_lon), max(murica_lon), min(murica_lat), max(murica_lat)) marker2.y = [37.6819] marker2.x = [-121.7681] marker2.size = 20 text = vcs.createtext() text.string = ["You are here"] text.viewport = marker2.viewport text.worldcoordinate = marker2.worldcoordinate text.x = [-121.7681] text.y = [37.6819] text.height = 8 x.plot(marker2) x.plot(text) raw_input("enter")
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))
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
templ_2.move(0.63, "x") templ_2.move(0.4, "y") templ_2.blank() templ_2.data.priority = 1 x.plot(murica, templ_2) marker2 = vcs.createmarker() marker2.type = "cross" marker2.viewport = (templ_2.data.x1, templ_2.data.x2, templ_2.data.y1, templ_2.data.y2) murica_lat = murica.getLatitude() murica_lon = murica.getLongitude() marker2.worldcoordinate = (min(murica_lon), max(murica_lon), min(murica_lat), max(murica_lat)) marker2.y = [37.6819] marker2.x = [-121.7681] marker2.size = 20 text = vcs.createtext() text.string = ["You are here"] text.viewport = marker2.viewport text.worldcoordinate = marker2.worldcoordinate text.x = [-121.7681] text.y = [37.6819] text.height = 8 x.plot(marker2) x.plot(text) raw_input("enter")
def plot_portrait( stat_xy, # array to visualize imgName='portrait_plot', # file name plotTitle=None, # title string on top img_length=800, img_height=600, # image size in pixel colormap='viridis', clevels=None, ccolors=None, # colormap and levels xtic_textsize=None, ytic_textsize=None, # font size for axes tic labels parea=None, # plotting area in ratio, in purpose of margin control missing_color='black', # color for missing data box Annotate=False, stat_xy_annotate=None, # annotation (showing value number in each box) num_box_partitioning=1, stat_xy_2=None, stat_xy_3=None, stat_xy_4=None, # additional triangle logo=True, GridMeshLine=True, # miscellaneous ): """ NOTE: Input - stat_xy: cdms2 MV2 2D array with proper axes decorated, values to visualize. - imgName: string, file name for PNG image file (e.g., 'YOUR_PLOT.png' or 'YOUR_PLOT'. If .png is not included, it will be added, so no worry). - plotTilte: string - img_length: integer, pixels for image file length. default=800. - img_height: integer, pixels for image file height. default=600. - colormap: string or actual VCS colormap. Default is 'viridis' that is default in VCS. - clevels: list of numbers (int or float). Colorbar levels. If not given automatically generated. - ccolors: list of colors. If not given automatically generate. - xtic_textsize: int, size of text for x-axis tic. If not given automatically generated. - ytic_textsize: int, size of text for y-axis tic. If not given automatically generated. - parea: list or tuple of float numbers between 0 to 1. Plotting area: (x1, x2, y1, y2). If not given automatically placed. - missing_color: string or color code (tuple or list of R, G, B, alpha). Color for missing data box. Default is 'black' - Annotate: bool, default=False. If Annotate, show numbers in individual boxes. - stat_xy_annotate: cdms2 MV2 2D array with proper axes decorated. Only needed when number to show as value annotated is not corresponding to the colormap. Not even bother when Annotate=False. For example, color for values those normalized by median, while annotate actual value for metrics. - num_box_partitioning: integer. How many partitioning in a box? e.g., 4: 4 triangles in each box. Default=1, should be less equal than 4. - stat_xy_2: cdms2 MV2 2D array. Stat for 2nd triangle in box. Default=None - stat_xy_3: cdms2 MV2 2D array. Stat for 3rd triangle in box. Default=None - stat_xy_4: cdms2 MV2 2D array. Stat for 4th triangle in box. Default=None - logo: bool, default=True. If False, CDAT logo turned off - GridMeshLine: bool, default=True. If False, no lines for boundary of individual boxes Output - PNG image file """ # VCS Canvas x = vcs.init(bg=True, geometry=(img_length, img_height)) # CDAT logo control if not logo: x.drawlogooff() # Set up Portrait Plot """ If you are NOT using JUPYTER NOTEBOOK, it is okay to DEACTIVATE below line and ACTIVATE second below line, and skip the "Prepare the Notebook" part above. """ #P = PortraitNotebook(x) P = pcmdi_metrics.graphics.portraits.Portrait() # # Preprocessing step to "decorate" the axis # axes = stat_xy.getAxisList() xax = [t + ' ' for t in list(axes[1][:])] yax = [t + ' ' for t in list(axes[0][:])] P.decorate(stat_xy, yax, xax) # # Customize # SET = P.PLOT_SETTINGS # Viewport on the Canvas if parea is not None: SET.x1, SET.x2, SET.y1, SET.y2 = parea # Both X (horizontal) and y (VERTICAL) ticks # Text table SET.tictable = vcs.createtexttable() SET.tictable.color = "black" # X (bottom) ticks # Text Orientation SET.xticorientation = vcs.createtextorientation() SET.xticorientation.angle = -90 SET.xticorientation.halign = "right" if xtic_textsize: SET.xticorientation.height = xtic_textsize # Y (vertical) ticks SET.yticorientation = vcs.createtextorientation() SET.yticorientation.angle = 0 SET.yticorientation.halign = "right" if ytic_textsize: SET.yticorientation.height = ytic_textsize # We can turn off the "grid" if needed if GridMeshLine: SET.draw_mesh = "y" else: SET.draw_mesh = "n" # Color for missing data SET.missing_color = missing_color # Timestamp SET.time_stamp = None # Colormap SET.colormap = colormap if clevels: SET.levels = clevels if ccolors: SET.fillareacolors = ccolors # Annotated Plot (i.e. show value number in boxes) if Annotate: SET.values.show = True if stat_xy_annotate is None: SET.values.array = stat_xy else: SET.values.array = stat_xy_annotate # Check before plotting if num_box_partitioning > 4: sys.exit('ERROR: num_box_partitioning should be less equal than 4') # # Plot # P.plot(stat_xy, multiple=pp_multiple(1, num_box_partitioning), x=x) # Add triangles if needed # Decorate additional arrays with empty string axes to avoid overwriting same information (if not, font will look ugly) xax_empty = [' ' for t in stat_xy.getAxis(1)[:]] yax_empty = [' ' for t in stat_xy.getAxis(0)[:]] if stat_xy_2 is not None: P.decorate(stat_xy_2, yax_empty, xax_empty) P.plot(stat_xy_2, x=x, multiple=pp_multiple(2, num_box_partitioning)) if stat_xy_3 is not None: P.decorate(stat_xy_3, yax_empty, xax_empty) P.plot(stat_xy_3, x=x, multiple=pp_multiple(3, num_box_partitioning)) if stat_xy_4 is not None: P.decorate(stat_xy_4, yax_empty, xax_empty) P.plot(stat_xy_4, x=x, multiple=pp_multiple(4, num_box_partitioning)) # Plot title if plotTitle: plot_title = vcs.createtext() plot_title.x = .5 plot_title.y = (SET.y2 + 1) / 2. plot_title.height = 30 plot_title.halign = 'center' plot_title.valign = 'half' plot_title.color = 'black' plot_title.string = plotTitle x.plot(plot_title) # Save if imgName.split('.')[-1] not in ['PNG', 'png']: imgName = imgName + '.png' x.png(imgName) # Preserve original axes stat_xy.setAxisList(axes) return P
def plot_map(mode, model, syear, eyear, season, eof_Nth, frac_Nth, output_file_name): # Create a VCS canvas canvas = vcs.init(geometry=(900, 800), bg=1) # Plotting in background mode # Turn off unnecessary information, avoiding text overlapping canvas.drawlogooff() tmpl = vcs.createtemplate() tmpl.blank([ 'title', 'mean', 'min', 'max', 'dataname', 'crdate', 'crtime', 'units', 'zvalue', 'tvalue', 'xunits', 'yunits', 'xname', 'yname' ]) # Color scheme and levels canvas.setcolormap('bl_to_darkred') gm = canvas.createisofill() # Graphic method if mode.split('_')[0] in ['PDO', 'NPGO']: gm.levels = [-0.5, -0.4, -0.3, -0.2, -0.1, 0, 0.1, 0.2, 0.3, 0.4, 0.5] else: gm.levels = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5] gm.ext_1 = 'y' # Extend left side colorbar edge gm.ext_2 = 'y' # Extend right side colorbar edge cols = vcs.getcolors(gm.levels, list(range(16, 240)), split=0) gm.fillareacolors = cols gm.missing = 0 # Map Projection if mode in ['NAO', 'PNA', 'NPO', 'PDO', 'AMO', 'NPGO']: gm.projection = 'lambert' elif mode in ['PDO_teleconnection', 'NPGO_teleconnection']: gm.projection = 'robinson' else: gm.projection = 'polar' tmpl.ytic1.priority = 0 tmpl.ytic2.priority = 0 # Remove white gap along longitude 0 when plot on polar projection if mode.split('_')[0] in ['SAM', 'NAM']: eof_Nth = eof_Nth(longitude=(-180, 185)) # Plotting domain xtra = {} if mode.split('_')[0] in ['PDO', 'NPGO']: # Global pass elif mode.split('_')[0] == 'SAM': # Southern Hemisphere xtra['latitude'] = (-90.0, 0.0) else: # Northern Hemisphere xtra['latitude'] = (90.0, 0.0) eof_Nth = eof_Nth(**xtra) # Plot canvas.plot(eof_Nth, gm, tmpl) # Title plot_title = vcs.createtext() plot_title.x = .5 plot_title.y = .97 plot_title.height = 30 plot_title.halign = 'center' plot_title.valign = 'top' plot_title.color = 'black' if frac_Nth != -999: percentage = str(round(float(frac_Nth*100.), 1)) + \ '%' # % with one floating number else: percentage = '' plot_title.string = mode+': '+model+'\n' + \ str(syear)+'-'+str(eyear)+' '+season+' '+percentage canvas.plot(plot_title) # Save image file canvas.png(output_file_name + '.png') # Close canvas canvas.clear() canvas.close()
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
] rgbs = [] for c in colors: r = int(c[1:3], 16) / 2.56 g = int(c[3:5], 16) / 2.56 b = int(c[5:], 16) / 2.56 rgbs.append([r, g, b]) colors = rgbs[:len(variables)] legend = vcs.createfillarea() legend.x = [] legend.y = [] legend.color = [] legend.viewport = [.1, .9, .05, t.xlabel1.y - .05] legend_labels = vcs.createtext() legend_labels.x = [] legend_labels.y = [] legend_labels.string = [] legend_labels.valign = "top" legend_labels.halign = "center" legend_labels.color = "black" legend_labels.viewport = legend.viewport oned.markersize = 5 for i, c, v, t in zip(range(len(variables)), colors, variables, templates): legend.x.append([ i / float(len(variables)), (i + 1) / float(len(variables)), (i + 1) / float(len(variables)), (i) / float(len(variables)) ]) legend.y.append([.25, .25, .5, .5]) legend.color.append(c)
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")