def postconfigure_plot(props): p = plot if chart.is_native_chart() else plt def get_prop(k): return props[k] if k in props else None if get_prop("yaxis_title"): p.xlabel(get_prop("xaxis_title")) if get_prop("yaxis_title"): p.ylabel(get_prop("yaxis_title")) if get_prop("xaxis_min"): p.xlim(left=float(get_prop("xaxis_min"))) if get_prop("xaxis_max"): p.xlim(right=float(get_prop("xaxis_max"))) if get_prop("yaxis_min"): p.ylim(bottom=float(get_prop("yaxis_min"))) if get_prop("yaxis_max"): p.ylim(top=float(get_prop("yaxis_max"))) if get_prop("xaxis_log"): p.xscale("log" if _parse_optional_bool(get_prop("xaxis_log")) else "linear") if get_prop("yaxis_log"): p.yscale("log" if _parse_optional_bool(get_prop("yaxis_log")) else "linear") legend(show=_parse_optional_bool(get_prop("legend_show")), frameon=_parse_optional_bool(get_prop("legend_border")), loc=get_prop("legend_placement")) p.grid(_parse_optional_bool(get_prop("grid_show")), "major" if (get_prop("grid_density") or "").lower() == "major" else "both") # grid_density is "Major" or "All" if not chart.is_native_chart(): plt.tight_layout()
def plot_histograms(df, props): p = plot if chart.is_native_chart() else plt def get_prop(k): return props[k] if k in props else None title_col, legend_cols = extract_label_columns(df) for i, t in enumerate(df.itertuples(index=False)): style = _make_histline_args(props, t, df) # We are branching here, and call the two .hist implementations # differently, because the MPL API does not have support for # underflows/overflows, so we have to "fake" them into the real # data as additional cells. Drawing them separately wouldn't # work, because that would change the histogram when the # "normalized" or "cumulative" transforms are done (by MPL). if chart.is_native_chart(): p.hist(t.binedges[:-1], t.binedges, weights=t.binvalues, label=make_legend_label(legend_cols, t), minvalue=t.min, maxvalue=t.max, underflows=t.underflows, overflows=t.overflows, **style) else: edges = list(t.binedges) values = list(t.binvalues) has_underflow_bin = not np.isnan(t.min) and not np.isnan( t.underflows) and t.min < edges[0] has_overflow_bin = not np.isnan(t.max) and not np.isnan( t.overflows) and t.max >= edges[-1] if has_underflow_bin: edges = [t.min] + edges values = [t.underflows] + values if has_overflow_bin: edges = edges + [t.max] values = values + [t.overflows] p.hist(edges[:-1], edges, weights=values, label=make_legend_label(legend_cols, t), **style) show_overflows = get_prop("show_overflows") if show_overflows and chart.is_native_chart(): plot.set_property("Hist.ShowOverflowCell", str(_parse_optional_bool(show_overflows)).lower()) title = get_prop("title") or make_chart_title(df, title_col, legend_cols) set_plot_title(title)
def _initialize_cycles(props): def get_prop(k): return props[k] if k in props else None global _marker_cycle global _color_cycle seed = int(get_prop('cycle_seed') or 0) r = random.Random(seed) ml = list("osv^<>pDd") if seed != 0: random.shuffle(ml, r.random) _marker_cycle = cycle(ml) prop_cycler = plt.rcParams['axes.prop_cycle'] if chart.is_native_chart(): num_colors = 10 else: num_colors = len(prop_cycler.by_key() ['color']) if "color" in prop_cycler.keys else 1 cl = ["C" + str(i) for i in range(num_colors)] if seed != 0: random.shuffle(cl, r.random) _color_cycle = cycle(cl)
def set_plot_title(title, suggested_chart_name=None): if chart.is_native_chart(): plot.title(title) else: plt.title(title) chart.set_suggested_chart_name( suggested_chart_name if suggested_chart_name is not None else title)
def plot_vectors(df, props): p = plot if chart.is_native_chart() else plt def get_prop(k): return props[k] if k in props else None column = "name" if get_prop("legend_labels") == "result names" else "title" title_col, legend_cols = extract_label_columns(df, column) for i, t in enumerate(df.itertuples(index=False)): style = _make_line_args(props, t, df) p.plot(t.vectime, t.vecvalue, label=make_legend_label(legend_cols, t), **style) title = get_prop("title") or make_chart_title(df, title_col, legend_cols) set_plot_title(title)
def preconfigure_plot(props): def get_prop(k): return props[k] if k in props else None if chart.is_native_chart(): #plot.set_properties(_filter_by_key_prefix(props,"plot.")) #TODO this was after plotting, was that intentional? supported_keys = plot.get_supported_property_keys() plot.set_properties({ k: v for k, v in props.items() if k in supported_keys}) plot.set_properties(parse_rcparams(get_prop("plot.properties") or "")) else: if get_prop("plt.style"): plt.style.use(get_prop("plt.style")) mpl.rcParams.update(_filter_by_key_prefix(props,"matplotlibrc.")) mpl.rcParams.update(parse_rcparams(get_prop("matplotlibrc") or "")) _initialize_cycles(props)
confidence_level = float(confidence_level_str[:-1]) / 100 conf_int = lambda values: utils.confidence_interval( confidence_level, values) if len(values) > 1 else math.nan pivoted = pd.pivot_table(df, values="value", columns=iso_itervars, index=xaxis_itervar if xaxis_itervar else "name", aggfunc=[np.mean, conf_int], dropna=False) df = pivoted["mean"] errors_df = pivoted["<lambda>"] legend_cols, _ = utils.extract_label_columns(df) p = plot if chart.is_native_chart() else plt try: xs = pd.to_numeric(df.index.values) p.xlabel(xaxis_itervar) except: xs = np.zeros_like(df.index.values) p.ylabel(scalar_names) for c in df.columns: style = utils._make_line_args(props, c, df) if len(xs) < 2 and style["marker"] == ' ': style["marker"] = '.' ys = df[c].values
def legend(*args, **kwargs): if chart.is_native_chart(): plot.legend(*args, **kwargs) else: _legend_mpl(*args, **kwargs)
def plot_bars(df, props, names=None, errors_df=None): p = plot if chart.is_native_chart() else plt def get_prop(k): return props[k] if k in props else None group_fill_ratio = 0.8 aligned_bar_fill_ratio = 0.9 overlap_visible_fraction = 1 / 3 # used only by the mpl charts xs = np.arange(len(df.index), dtype=np.float64) # the x locations for the groups width = group_fill_ratio / len(df.columns) # the width of the bars bottoms = np.zeros_like(xs) group_increment = 0.0 baseline = get_prop("baseline") if baseline: if chart.is_native_chart(): # is this how this should be done? plot.set_property("Bars.Baseline", baseline) else: bottoms += float(baseline) extra_args = dict() placement = get_prop("bar_placement") if placement: if chart.is_native_chart(): # is this how this should be done? plot.set_property("Bar.Placement", placement) else: extra_args["bottom"] = bottoms if placement == "InFront": width = group_fill_ratio elif placement == "Stacked": width = group_fill_ratio elif placement == "Aligned": width = group_fill_ratio / len(df.columns) group_increment = width xs -= width * (len(df.columns) - 1) / 2 width *= aligned_bar_fill_ratio elif placement == "Overlap": width = group_fill_ratio / ( 1 + len(df.columns) * overlap_visible_fraction) group_increment = width * overlap_visible_fraction extra_parts = (1.0 / overlap_visible_fraction - 1) xs += width / extra_parts - ( len(df.columns) + extra_parts) * width * overlap_visible_fraction / 2 for i, column in enumerate(df): style = _make_bar_args(props, df) if not chart.is_native_chart(): # FIXME: noot pretty... extra_args['zorder'] = 1 - (i / len(df.columns) / 10) label = df.columns.name + "=" + _to_label( column) if df.columns.name else _to_label(column) ys = df[column].values p.bar(xs, ys, width, label=label, **extra_args, **style) if not chart.is_native_chart() and errors_df is not None: plt.errorbar(xs, ys, yerr=errors_df[column], capsize=float(get_prop("cap_size") or 4), **style, linestyle="none", ecolor=mpl.rcParams["axes.edgecolor"]) xs += group_increment if placement == "Stacked": bottoms += df[column].values rotation = get_prop("xlabel_rotation") if rotation: rotation = float(rotation) else: rotation = 0 p.xticks(list(range(len(df.index))), list([_to_label(i) for i in df.index.values]), rotation=rotation) # Add some text for labels, title and custom x-axis tick labels, etc. groups = (get_prop("groups") or "").split(",") series = (get_prop("series") or "").split(",") p.xlabel(_to_label(df.index.names[0])) title = "" if len(names): names_str = [str(n) for n in names] groups_series_str = [str(gs) for gs in groups + series] p.ylabel(", ".join(names_str)) title = ", ".join(names_str) if groups_series_str and groups_series_str[0]: title += " by " + ", ".join(groups_series_str) set_plot_title(get_prop("title") or title)
unique_names = df["name"].unique() if len(unique_names) != 1: plot.set_warning("Scalar names should be unique") exit(1) scalar_name = unique_names[0] df = pd.pivot_table(df, values="value", columns=iso_itervar, index=xaxis_itervar) print(df) legend_cols, _ = utils.extract_label_columns(df) p = plot if chart.is_native_chart() else plt p.xlabel(xaxis_itervar) p.ylabel(scalar_name) try: xs = pd.to_numeric(df.index.values) except: plot.set_warning( "The X axis itervar is not purely numeric, this is not supported yet.") exit(1) for i, c in enumerate(df.columns): style = utils._make_line_args(props, c, df) p.plot(xs, df[c].values,