def plot( self, context, output, bbox, crs, format, height, layers, styles, version, width, transparent, _macro=False, bgcolor=None, elevation=None, exceptions=None, time=None, ): lon_vertical = 0.0 if crs.startswith("EPSG:32661:"): crs_name = "polar_north" lon_vertical = float(crs.split(":")[2]) elif crs.startswith("EPSG:32761:"): crs_name = "polar_south" lon_vertical = float(crs.split(":")[2]) elif crs == "EPSG:32761": crs_name = "EPSG:32761" else: try: crs = _CRSS[crs] crs_name = crs.name except KeyError: raise ValueError("Unsupported CRS '{}'".format(crs)) try: magics_format = MAGICS_OUTPUT_TYPES[format] except KeyError: raise errors.InvalidFormat(format) output_fname = output.target(magics_format) path, _ = os.path.splitext(output_fname) with LOCK: min_x, min_y, max_x, max_y = bbox # Magics is talking in cm. width_cm = width / 40.0 height_cm = height / 40.0 macro.silent() coordinates_system = {"EPSG:4326": "latlon"} map_params = { "subpage_map_projection": crs_name, "subpage_lower_left_latitude": min_y, "subpage_lower_left_longitude": min_x, "subpage_upper_right_latitude": max_y, "subpage_upper_right_longitude": max_x, "subpage_coordinates_system": coordinates_system.get(crs_name, "projection"), "subpage_frame": "off", "page_x_length": width_cm, "page_y_length": height_cm, "super_page_x_length": width_cm, "super_page_y_length": height_cm, "subpage_x_length": width_cm, "subpage_y_length": height_cm, "subpage_x_position": 0.0, "subpage_y_position": 0.0, "output_width": width, "page_frame": "off", "skinny_mode": "on", "page_id_line": "off", } # add extra settings for polar stereographic projection when # vertical longitude is not 0 if crs_name in ["polar_north", "polar_south"]: map_params["subpage_map_vertical_longitude"] = lon_vertical if crs_name in ["polar_north"]: map_params["subpage_map_true_scale_north"] = 90 if crs_name in ["polar_south"]: map_params["subpage_map_true_scale_south"] = -90 args = [ macro.output( output_formats=[magics_format], output_name_first_page_number="off", output_cairo_transparent_background=transparent, output_width=width, output_name=path, ), macro.mmap(**map_params), ] for layer, style in zip(layers, styles): style = layer.style(style) args += layer.render(context, macro, style) if _macro: return ( "text/x-python", self.macro_text( args, output.target(".py"), getattr(context, "data_url", None), layers, styles, ), ) # self.log.debug('plot(): Calling macro.plot(%s)', args) try: macro.plot(*args) except Exception as e: self.log.exception("Magics error: %s", e) raise self.log.debug("plot(): Size of %s: %s", output_fname, os.stat(output_fname).st_size) return format, output_fname
# (C) Copyright 1996-2019 ECMWF. # # This software is licensed under the terms of the Apache Licence Version 2.0 # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. # In applying this licence, ECMWF does not waive the privileges and immunities # granted to it by virtue of its status as an intergovernmental organisation nor # does it submit to any jurisdiction. import cftime import xarray as xr import numpy as np from Magics import macro as magics ref = "xarray7" ds = xr.open_dataset('2dlatlon.nc') time = cftime.DatetimeNoLeap(2081, 2, 15, 0, 0, 0, 0, 5, 46) png = magics.output(output_name_first_page_number="off", output_name=ref) data = magics.mxarray(xarray_dataset=ds, xarray_variable_name="sic", xarray_dimension_settings={ "bnds": 1.0, "time": time }) contour = magics.mcont(contour_automatic_setting="ecmwf") magics.plot(png, data, contour, magics.mcoast())
data = magics.minput( input_field=values, input_field_initial_latitude=firstlat, input_field_latitude_step=steplat, input_field_initial_longitude=firstlon, input_field_longitude_step=steplon, input_mars_metadata=json.dumps(metadata), ) #Setting the field contour contour = magics.mcont(contour_shade="on", legend="on", legend_display_type="continuous", contour_highlight="off", contour_shade_method="area_fill", contour_shade_colour_direction="clockwise", contour_shade_colour_method="calculate", contour_shade_max_level_colour="red", contour_shade_min_level_colour=" blue") eccharts = magics.mcont(contour_automatic_setting="ecchart") #Setting the title title = magics.mtext(text_lines=["Using Grib API and arrays..."], text_colour="charcoal", text_font_size='0.8', text_justification='left') #Plot the map magics.plot(output, europe, data, eccharts, magics.mcoast(), title)
#TODO: fileout handling fileout=str(args.product) + '+' + str(k).zfill(2) out = mm.output( output_name = args.outdir + "/" + fileout, output_formats=['png'], output_name_first_page_number = "off", output_width = 1280 ) title = mm.mtext( text_lines = ["<grib_info key='nameECMF'/> - <grib_info key='valid-date'/>"], text_colour = 'black', text_font_size = 1.0, text_justification = "left", text_font_style='bold', text_mode = 'positional', text_box_X_position = 1., text_box_Y_position = 17.5 ) # cleanup json for unwanted parameters # (they show up as warnings in Magics output) shading_opt = mm_fields[args.product].copy() del shading_opt['magic_func'] del shading_opt['nameECMF'] shading = getattr(mm, mm_fields[args.product]['magic_func'])(**shading_opt) mm.plot(out, area, bg, input_data, shading, legend, fg, title)
def plot(*args, **kwargs): return macro.plot(*args, **kwargs)
from Magics import macro as magics #name = 'magics' #Setting of the output file name output = magics.output(output_formats=['png'], output_name_first_page_number="off", output_name="mymagicsplot") #Import the data data = magics.mnetcdf(netcdf_filename="test.nc", netcdf_value_variable="aps") #Apply styling legend = magics.mlegend() contour = magics.mcont(contour_shade="on", contour_shade_method="area_fill", legend='on') coast = magics.mcoast() # Make the plot magics.plot(output, data, contour, coast, legend)
projection = mag.mmap(super_page_x_length=width + 3, super_page_y_length=height + 4, subpage_x_position=2.2, subpage_y_position=2.8, subpage_x_length=width, subpage_y_length=height, subpage_map_projection='cartesian', subpage_x_axis_type='date', subpage_y_axis_type='regular', subpage_x_date_min=min_date, subpage_x_date_max=max_date, subpage_y_min=min_y, subpage_y_max=max_y, page_id_line="off") mag.plot( myoutput, projection, vertical, horizontal, low_input, low_graph, medium_input, medium_graph, high_input, high_graph, extreme_input, extreme_graph, )
def plot_in_magics_boxplot(path, date, pointname, var, meta, y_axis_range, filename, lead_times,\ data_percentiles_eu_eps, point_values_eu_det): run_time = datetime.datetime(date['year'], date['month'], date['day'], date['hour']) if var == 't_2m' or var == 'wind_10m' or var == 'mslp' or var == 'clct': lead_times = [-1.0 * x for x in lead_times] elif var == 'prec_rate' or var == 'direct_rad' or var == 'diffuse_rad': lead_times = [-1.0 * x for x in lead_times] time_start = -123. time_end = 3. output_layout = magics.output( output_formats=['png'], output_name=path['base'] + path['plots'] + filename, output_name_first_page_number='off', output_width=1500, super_page_x_length=15.0, super_page_y_length=6.0, ) page_layout = magics.page( layout='positional', page_x_position=0.0, page_y_position=0.0, page_x_length=15.0, page_y_length=6.0, page_id_line='off', ) coord_system = magics.mmap( subpage_map_projection='cartesian', subpage_x_min=time_start, subpage_x_max=time_end, subpage_y_min=y_axis_range['min'], subpage_y_max=y_axis_range['max'], subpage_x_position=1.0, subpage_y_position=0.48, subpage_x_length=13.7, subpage_y_length=5.0, ) vertical_axis = magics.maxis( axis_orientation='vertical', axis_grid='on', axis_tick_label_height=0.7, axis_grid_thickness=1, axis_grid_line_style='dash', axis_tick_interval=y_axis_range['interval'], ) horizontal_axis = magics.maxis( axis_tick_interval=24, axis_tick_label='off', axis_title='off', ) ######################################################################## ##### icon-eu-eps ##### bar_minmax_eu = magics.mgraph( graph_type='bar', graph_bar_colour='black', graph_bar_width=0.05, ) data_minmax_eu = magics.minput( input_x_values=lead_times, input_y_values=data_percentiles_eu_eps[:, 0], input_y2_values=data_percentiles_eu_eps[:, 6], ) bar1090_eu = magics.mgraph( graph_type='bar', graph_bar_colour='rgb(0, 150, 130)', # KIT turquoise graph_bar_width=0.5, ) data1090_eu = magics.minput( input_x_values=lead_times, input_y_values=data_percentiles_eu_eps[:, 1], input_y2_values=data_percentiles_eu_eps[:, 5], ) bar2575_eu = magics.mgraph( graph_type='bar', graph_bar_colour='rgb(0, 150, 130)', # KIT turquoise graph_bar_width=1.0, legend='on', legend_user_text='<font colour="black"> ICON-EU-EPS (20km)</font>') data2575_eu = magics.minput( input_x_values=lead_times, input_y_values=data_percentiles_eu_eps[:, 2], input_y2_values=data_percentiles_eu_eps[:, 4], ) bar_median_eu = magics.mgraph( graph_type='bar', graph_bar_colour='black', graph_bar_width=1.0, ) data_median_eu = magics.minput( input_x_values=lead_times, input_y_values=data_percentiles_eu_eps[:, 3] - (y_axis_range['max'] - y_axis_range['min']) / 400., input_y2_values=data_percentiles_eu_eps[:, 3] + (y_axis_range['max'] - y_axis_range['min']) / 400., ) ##### icon-eu ##### bar_eu_det = magics.mgraph( graph_line='off', graph_symbol='on', graph_symbol_marker_index=15, graph_symbol_height=0.2, graph_symbol_colour='white', graph_symbol_outline='on', graph_symbol_outline_colour='black', graph_symbol_outline_thickness=3, legend='on', legend_user_text='<font colour="black"> ICON-EU-DET (6.5km)</font>') data_eu_det = magics.minput( input_x_values=lead_times, input_y_values=point_values_eu_det[:], ) ######################################################################## analysis_line = magics.mgraph( graph_line_colour='rgb(0, 242, 209)', # bright turquoise graph_line_thickness=3, legend='on', legend_user_text= '<font colour="black"> ICON-EU-DET (6.5km), 0h-Forecast</font>') analysis_value = magics.minput( input_x_values=[time_start, time_end], input_y_values=[y_axis_range['analysis'], y_axis_range['analysis']]) if var == 't_2m' or var == 'mslp': ref_th = 5 else: ref_th = 0 ref_level_line = magics.mgraph( graph_line_colour='black', graph_line_thickness=ref_th, ) ref_level_value = magics.minput( input_x_values=[time_start, time_end], input_y_values=[y_axis_range['ref'], y_axis_range['ref']]) ######################################################################## if var == 'direct_rad' or var == 'diffuse_rad': long_title_adjustment = 0.7 else: long_title_adjustment = 0.0 title_str = '{} in {}'.format(meta['var'], pointname) title = magics.mtext( text_line_1=title_str, text_font_size=1.0, text_colour='black', text_justification='centre', text_mode='positional', text_box_x_position=5.3 + long_title_adjustment, text_box_y_position=5.45, text_box_x_length=5.0, text_box_y_length=0.7, ) ######################################################################## timeshift = get_timeshift() initial_time = run_time.hour + timeshift if timeshift == 1: time_code = 'CET' # UTC+1 elif timeshift == 2: time_code = 'CEST' # UTC+2 if var == 'prec_rate' or var == 'direct_rad' or var == 'diffuse_rad': initial_time2 = initial_time + 6 if initial_time2 == 26: initial_time2 = 2 init_time_str = 'Forecast time: {}, {:02}-{:02}{}'.format(\ run_time.strftime('%a., %d %b. %Y'), initial_time, initial_time2, time_code) else: init_time_str = 'Forecast time: {}, {:02}{}'.format(\ run_time.strftime('%a., %d %b. %Y'), initial_time, time_code) init_time = magics.mtext( text_line_1=init_time_str, text_font_size=0.8, text_colour='black', text_justification='left', text_mode='positional', text_box_x_position=1.0, text_box_y_position=5.45, text_box_x_length=1.5, text_box_y_length=0.5, ) unit_str = meta['units'] unit = magics.mtext( text_line_1=unit_str, text_font_size=0.8, text_colour='black', text_justification='right', text_mode='positional', text_box_x_position=0.31, text_box_y_position=5.55, text_box_x_length=0.5, text_box_y_length=0.5, ) if var == 't_2m': unit_special_str = 'o' correction = -0.12 elif var == 'direct_rad' or var == 'diffuse_rad': unit_special_str = '2' correction = 0.06 else: unit_special_str = '' correction = 0 unit_special = magics.mtext( text_line_1=unit_special_str, text_font_size=0.4, text_colour='black', text_justification='right', text_mode='positional', text_box_x_position=0.31 + correction, text_box_y_position=5.55 + 0.14, text_box_x_length=0.5, text_box_y_length=0.5, ) logo = magics.mimport( import_file_name=path['base'] + 'plots/logo/' + 'w2w_icon.png', import_x_position=13.74, import_y_position=5.52, import_height=0.474, import_width=1.000, ) legend = magics.mlegend( legend_text_font_size=0.8, legend_box_mode='positional', legend_box_x_position=5.0, legend_box_y_position=5.03, legend_box_x_length=9.0, legend_box_y_length=0.5, legend_entry_text_width=90, ) time_labels = ['-120h', '-96h', '-72h', '-48h', '-24h', '0h'] spacing = 2.61 left_pos = 0.58 date1_label = magics.mtext( text_line_1=time_labels[0], text_font_size=0.8, text_colour='black', text_justification='centre', text_mode='positional', text_box_x_position=left_pos + 0 * spacing, text_box_y_position=0.0, text_box_x_length=1.5, text_box_y_length=0.3, text_border='off', ) date2_label = magics.mtext( text_line_1=time_labels[1], text_font_size=0.8, text_colour='black', text_justification='centre', text_mode='positional', text_box_x_position=left_pos + 1 * spacing, text_box_y_position=0.0, text_box_x_length=1.5, text_box_y_length=0.3, text_border='off', ) date3_label = magics.mtext( text_line_1=time_labels[2], text_font_size=0.8, text_colour='black', text_justification='centre', text_mode='positional', text_box_x_position=left_pos + 2 * spacing, text_box_y_position=0.0, text_box_x_length=1.5, text_box_y_length=0.3, text_border='off', ) date4_label = magics.mtext( text_line_1=time_labels[3], text_font_size=0.8, text_colour='black', text_justification='centre', text_mode='positional', text_box_x_position=left_pos + 3 * spacing, text_box_y_position=0.0, text_box_x_length=1.5, text_box_y_length=0.3, text_border='off', ) date5_label = magics.mtext( text_line_1=time_labels[4], text_font_size=0.8, text_colour='black', text_justification='centre', text_mode='positional', text_box_x_position=left_pos + 4 * spacing, text_box_y_position=0.0, text_box_x_length=1.5, text_box_y_length=0.3, text_border='off', ) date6_label = magics.mtext( text_line_1=time_labels[5], text_font_size=0.8, text_colour='black', text_justification='centre', text_mode='positional', text_box_x_position=left_pos + 5 * spacing, text_box_y_position=0.0, text_box_x_length=1.5, text_box_y_length=0.3, text_border='off', ) magics.context.silent = True magics.plot( output_layout, page_layout, coord_system, vertical_axis, horizontal_axis, ref_level_value, ref_level_line, data_minmax_eu, bar_minmax_eu, data1090_eu, bar1090_eu, data2575_eu, bar2575_eu, data_median_eu, bar_median_eu, data_eu_det, bar_eu_det, analysis_value, analysis_line, title, init_time, unit, unit_special, logo, legend, date1_label, date2_label, date3_label, date4_label, date5_label, date6_label, ) return
import Magics.macro as magics # Setting the projection projection = magics.mmap(subpage_map_projection="lambert", subpage_lower_left_latitude=-0.00, subpage_lower_left_longitude=-80.00, subpage_upper_right_latitude=70.00, subpage_upper_right_longitude=160.00, subpage_map_area_definition="corners", page_id_line="off") # Defining the coastlines coast = magics.mcoast(map_coastline_resolution="automatic", map_coastline_colour="tan", map_coastline_land_shade="on", map_coastline_land_shade_colour="cream", map_grid="on", map_grid_line_style="dot", map_grid_colour="tan") png = magics.output(output_formats=['png'], output_name_first_page_number="off", output_name="my_png") magics.plot(png, projection, coast)
def legend(self, context, output, format, height, layer, style, version, width, transparent ): try: magics_format = MAGICS_OUTPUT_TYPES[format] except KeyError: raise errors.InvalidFormat(format) output_fname = output.target(magics_format) path, _ = os.path.splitext(output_fname) with LOCK: # Magics is talking in cm. width_cm = float(width) / 40. height_cm = float(height) / 40. args = [ macro.output(output_formats=[magics_format], output_name_first_page_number='off', output_cairo_transparent_background=transparent, output_width=width, output_name=path), macro.mmap( subpage_frame='off', page_x_length=width_cm, page_y_length=height_cm, super_page_x_length=width_cm, super_page_y_length=height_cm, subpage_x_length=width_cm, subpage_y_length=height_cm, subpage_x_position=0., subpage_y_position=0., output_width=width, page_frame='off', page_id_line='off',), ] contour = layer.style(style, ) args += layer.render(context, macro, contour, {'legend': 'on', "contour_legend_only": True}) legend_font_size = "25%" if width_cm < height_cm: legend_font_size = "5%" legend = macro.mlegend( legend_title="on", legend_title_text=layer.title, legend_display_type="continuous", legend_box_mode="positional", legend_only=True, legend_box_x_position=0.00, legend_box_y_position=0.00, legend_box_x_length=width_cm, legend_box_y_length=height_cm, legend_box_blanking=not transparent, legend_text_font_size=legend_font_size, legend_text_colour="navy", ) # self.log.debug('plot(): Calling macro.plot(%s)', args) try: macro.plot(*args, legend) except Exception as e: self.log.exception('Magics error: %s', e) raise self.log.debug('plot(): Size of %s: %s', output_fname, os.stat(output_fname).st_size) return output_fname