Create shared properties for scatter / line plot.
339653
def _scatter_or_line(h1: Histogram1D, mark_template: list, kwargs: dict) -> dict:
    """"""
    from physt.histogram_collection import HistogramCollection
    if isinstance(h1, HistogramCollection):
        collection = h1
        h1 = h1[0]
    else:
        collection = HistogramCollection(h1)

    vega = _create_figure(kwargs)

    legend = kwargs.pop("legend", len(collection) > 1)

    vega["data"] = [
        {
            "name": "table",
            "values": []
        },
        {
            "name": "labels",
            "values": [h.name for h in collection]
        }]

    for hist_i, histogram in enumerate(collection):
        centers = histogram.bin_centers.tolist()
        data = get_data(histogram, kwargs.pop("density", None), kwargs.pop("cumulative", None)).tolist()
        vega["data"][0]["values"] += [{"x": centers[i], "y": data[i], "c": hist_i} for i in range(histogram.bin_count)]

    _add_title(collection, vega, kwargs)
    _create_scales(collection, vega, kwargs)
    _create_axes(collection, vega, kwargs)
    _create_series_scales(vega)
    _create_series_faceted_marks(vega, mark_template)
    _create_tooltips(h1, vega, kwargs)  # TODO: Make it work!
    if legend:
        _create_series_legend(vega)

    return vega
843044
def _maketicks(self, ax, units='THz'):
        """"""
        # set y-ticks
        ax.yaxis.set_major_locator(MaxNLocator(6))
        ax.yaxis.set_minor_locator(AutoMinorLocator(2))
        ax.xaxis.set_minor_locator(AutoMinorLocator(2))

        # set x-ticks; only plot the unique tick labels
        ticks = self.get_ticks()
        unique_d = []
        unique_l = []
        if ticks['distance']:
            temp_ticks = list(zip(ticks['distance'], ticks['label']))
            unique_d.append(temp_ticks[0][0])
            unique_l.append(temp_ticks[0][1])
            for i in range(1, len(temp_ticks)):
                if unique_l[-1] != temp_ticks[i][1]:
                    unique_d.append(temp_ticks[i][0])
                    unique_l.append(temp_ticks[i][1])

        logging.info('\nLabel positions:')
        for dist, label in list(zip(unique_d, unique_l)):
            logging.info('\t{:.4f}: {}'.format(dist, label))

        ax.set_xticks(unique_d)
        ax.set_xticklabels(unique_l)
        ax.xaxis.grid(True, ls='-')

        trans_xdata_yaxes = blended_transform_factory(ax.transData,
                                                      ax.transAxes)
        ax.vlines(unique_d, 0, 1,
                  transform=trans_xdata_yaxes,
                  colors=rcParams['grid.color'],
                  linewidth=rcParams['grid.linewidth'])

        # Use a text hyphen instead of a minus sign because some nice fonts
        # like Whitney don't come with a real minus
        labels = {'thz': 'THz', 'cm-1': r'cm$^{\mathrm{-}\mathregular{1}}$',
                  'ev': 'eV', 'mev': 'meV'}
        ax.set_ylabel('Frequency ({0})'.format(labels[units.lower()]))
1237325
def _makeplot(self, ax, fig, data, zero_to_efermi=True,
                  vbm_cbm_marker=False, ymin=-6., ymax=6.,
                  height=None, width=None,
                  dos_plotter=None, dos_options=None, dos_label=None,
                  aspect=None):
        """"""
        # draw line at Fermi level if not zeroing to e-Fermi
        if not zero_to_efermi:
            ytick_color = rcParams['ytick.color']
            ef = self._bs.efermi
            ax.axhline(ef, color=ytick_color)

        # set x and y limits
        ax.set_xlim(0, data['distances'][-1][-1])
        if self._bs.is_metal() and not zero_to_efermi:
            ax.set_ylim(self._bs.efermi + ymin, self._bs.efermi + ymax)
        else:
            ax.set_ylim(ymin, ymax)

        if vbm_cbm_marker:
            for cbm in data['cbm']:
                ax.scatter(cbm[0], cbm[1], color='C2', marker='o', s=100)
            for vbm in data['vbm']:
                ax.scatter(vbm[0], vbm[1], color='C3', marker='o', s=100)

        if dos_plotter:
            ax = fig.axes[1]

            if not dos_options:
                dos_options = {}

            dos_options.update({'xmin': ymin, 'xmax': ymax})
            self._makedos(ax, dos_plotter, dos_options, dos_label=dos_label)
        else:
            # keep correct aspect ratio for axes based on canvas size
            x0, x1 = ax.get_xlim()
            y0, y1 = ax.get_ylim()
            if width is None:
                width = rcParams['figure.figsize'][0]
            if height is None:
                height = rcParams['figure.figsize'][1]

            if not aspect:
                aspect = height / width

            ax.set_aspect(aspect * ((x1 - x0) / (y1 - y0)))
162921
def line_plot(self, x='year', y='value', **kwargs):
        
        df = self.as_pandas(with_metadata=kwargs)

        # pivot data if asked for explicit variable name
        variables = df['variable'].unique()
        if x in variables or y in variables:
            keep_vars = set([x, y]) & set(variables)
            df = df[df['variable'].isin(keep_vars)]
            idx = list(set(df.columns) - set(['value']))
            df = (df
                  .reset_index()
                  .set_index(idx)
                  .value  # df -> series
                  .unstack(level='variable')  # keep_vars are columns
                  .rename_axis(None, axis=1)  # rm column index name
                  .reset_index()
                  .set_index(META_IDX)
                  )
            if x != 'year' and y != 'year':
                df = df.drop('year', axis=1)  # years causes NaNs

        ax, handles, labels = plotting.line_plot(
            df.dropna(), x=x, y=y, **kwargs)
        return ax
377439
def finalize(self, **kwargs):
        
        # Divide out the two features
        feature_one, feature_two = self.features_

        # Set the title
        self.set_title('Scatter Plot: {0} vs {1}'.format(
            str(feature_one), str(feature_two)))
        # Add the legend
        self.ax.legend(loc='best')
        self.ax.set_xlabel(str(feature_one))
        self.ax.set_ylabel(str(feature_two))
122120
function () {
            var plotLine = this,
              axis = plotLine.axis,
              horiz = axis.horiz,
              halfPointRange = (axis.pointRange || 0) / 2,
              options = plotLine.options,
              optionsLabel = options.label,
              label = plotLine.label,
              width = options.width,
              to = options.to,
              from = options.from,
              isBand = defined(from) && defined(to),
              value = options.value,
              dashStyle = options.dashStyle,
              svgElem = plotLine.svgElem,
              path = [],
              addEvent,
              eventType,
              xs,
              ys,
              x,
              y,
              color = options.color,
              zIndex = options.zIndex,
              events = options.events,
              attribs = {},
              renderer = axis.chart.renderer;

            // logarithmic conversion
            if (axis.isLog) {
                from = log2lin(from);
                to = log2lin(to);
                value = log2lin(value);
            }

            // plot line
            if (width) {
                path = axis.getPlotLinePath(value, width);
                attribs = {
                    stroke: color,
                    'stroke-width': width
                };
                if (dashStyle) {
                    attribs.dashstyle = dashStyle;
                }
            } else if (isBand) { // plot band

                // keep within plot area
                from = mathMax(from, axis.min - halfPointRange);
                to = mathMin(to, axis.max + halfPointRange);

                path = axis.getPlotBandPath(from, to, options);
                if (color) {
                    attribs.fill = color;
                }
                if (options.borderWidth) {
                    attribs.stroke = options.borderColor;
                    attribs['stroke-width'] = options.borderWidth;
                }
            } else {
                return;
            }
            // zIndex
            if (defined(zIndex)) {
                attribs.zIndex = zIndex;
            }

            // common for lines and bands
            if (svgElem) {
                if (path) {
                    svgElem.animate({
                        d: path
                    }, null, svgElem.onGetPath);
                } else {
                    svgElem.hide();
                    svgElem.onGetPath = function () {
                        svgElem.show();
                    };
                    if (label) {
                        plotLine.label = label = label.destroy();
                    }
                }
            } else if (path && path.length) {
                plotLine.svgElem = svgElem = renderer.path(path)
                  .attr(attribs).add();

                // events
                if (events) {
                    addEvent = function (eventType) {
                        svgElem.on(eventType, function (e) {
                            events[eventType].apply(plotLine, [e]);
                        });
                    };
                    for (eventType in events) {
                        addEvent(eventType);
                    }
                }
            }

            // the plot band/line label
            if (optionsLabel && defined(optionsLabel.text) && path && path.length && axis.width > 0 && axis.height > 0) {
                // apply defaults
                optionsLabel = merge({
                    align: horiz && isBand && 'center',
                    x: horiz ? !isBand && 4 : 10,
                    verticalAlign : !horiz && isBand && 'middle',
                    y: horiz ? isBand ? 16 : 10 : isBand ? 6 : -4,
                    rotation: horiz && !isBand && 90
                }, optionsLabel);

                // add the SVG element
                if (!label) {
                    attribs = {
                        align: optionsLabel.textAlign || optionsLabel.align,
                        rotation: optionsLabel.rotation
                    };
                    if (defined(zIndex)) {
                        attribs.zIndex = zIndex;
                    }
                    plotLine.label = label = renderer.text(
                      optionsLabel.text,
                      0,
                      0,
                      optionsLabel.useHTML
                      )
                      .attr(attribs)
                      .css(optionsLabel.style)
                      .add();
                }

                // get the bounding box and align the label
                // #3000 changed to better handle choice between plotband or plotline
                xs = [path[1], path[4], (isBand ? path[6] : path[1])];
                ys = [path[2], path[5], (isBand ? path[7] : path[2])];
                x = arrayMin(xs);
                y = arrayMin(ys);

                label.align(optionsLabel, false, {
                    x: x,
                    y: y,
                    width: arrayMax(xs) - x,
                    height: arrayMax(ys) - y
                });
                label.show();

            } else if (label) { // move out of sight
                label.hide();
            }

            // chainable
            return plotLine;
        }
567830
def PyplotLineStyles():
    
    import numpy as np
    import matplotlib.pyplot as plt
    from collections import OrderedDict
    from matplotlib.transforms import blended_transform_factory

    linestyles = OrderedDict(
        [('solid', (0, ())),
         ('loosely dotted', (0, (1, 10))),
         ('dotted', (0, (1, 5))),
         ('densely dotted', (0, (1, 1))),

         ('loosely dashed', (0, (5, 10))),
         ('dashed', (0, (5, 5))),
         ('densely dashed', (0, (5, 1))),

         ('loosely dashdotted', (0, (3, 10, 1, 10))),
         ('dashdotted', (0, (3, 5, 1, 5))),
         ('densely dashdotted', (0, (3, 1, 1, 1))),

         ('loosely dashdotdotted', (0, (3, 10, 1, 10, 1, 10))),
         ('dashdotdotted', (0, (3, 5, 1, 5, 1, 5))),
         ('densely dashdotdotted', (0, (3, 1, 1, 1, 1, 1)))])

    plt.figure(figsize=(10, 6))
    ax = plt.subplot(1, 1, 1)

    X, Y = np.linspace(0, 100, 10), np.zeros(10)
    for i, (name, linestyle) in enumerate(linestyles.items()):
        ax.plot(X, Y + i, linestyle=linestyle, linewidth=1.5, color='black')

    ax.set_ylim(-0.5, len(linestyles) - 0.5)
    plt.yticks(np.arange(len(linestyles)), linestyles.keys())
    plt.xticks([])

    # For each line style, add a text annotation with a small offset from
    # the reference point (0 in Axes coords, y tick value in Data coords).
    reference_transform = blended_transform_factory(ax.transAxes, ax.transData)
    for i, (name, linestyle) in enumerate(linestyles.items()):
        ax.annotate(str(linestyle), xy=(0.0, i), xycoords=reference_transform,
                    xytext=(-6, -12), textcoords='offset points', color="blue",
                    fontsize=8, ha="right", family="monospace")

    plt.tight_layout()
    return plt.gcf()
979215
def create_geoms(self, gdefs, plot):
        
        new_gdefs = []
        for gdef in gdefs:
            gdef = gdef.create_geoms(plot)
            if gdef:
                new_gdefs.append(gdef)

        return new_gdefs
165172
def _pys2shape(self, line):
        """"""

        self.code_array.shape = self._get_key(*self._split_tidy(line))
336398
def scatter(self, x, y, **kwargs):
        
        variables = self.data['variable'].unique()
        xisvar = x in variables
        yisvar = y in variables
        if not xisvar and not yisvar:
            cols = [x, y] + self._discover_meta_cols(**kwargs)
            df = self.meta[cols].reset_index()
        elif xisvar and yisvar:
            # filter pivot both and rename
            dfx = (
                self
                .filter(variable=x)
                .as_pandas(with_metadata=kwargs)
                .rename(columns={'value': x, 'unit': 'xunit'})
                .set_index(YEAR_IDX)
                .drop('variable', axis=1)
            )
            dfy = (
                self
                .filter(variable=y)
                .as_pandas(with_metadata=kwargs)
                .rename(columns={'value': y, 'unit': 'yunit'})
                .set_index(YEAR_IDX)
                .drop('variable', axis=1)
            )
            df = dfx.join(dfy, lsuffix='_left', rsuffix='').reset_index()
        else:
            # filter, merge with meta, and rename value column to match var
            var = x if xisvar else y
            df = (
                self
                .filter(variable=var)
                .as_pandas(with_metadata=kwargs)
                .rename(columns={'value': var})
            )
        ax = plotting.scatter(df.dropna(), x, y, **kwargs)
        return ax
310702
def create_scatterplot(df):
    
    fig = Figure("/mg/scatter/", "mg_scatter")
    fig.layout.set_size(width=450, height=200)
    fig.layout.set_margin(left=40, right=40)
    fig.graphics.animate_on_load()

    init_params = {"Data": "Steps"}

    def get_data():
        y = request.args.get("Data", "Steps")
        return jsonify(ScatterPlot.to_json(df, "Steps", y))

    # Make a histogram with 20 bins
    return ScatterPlot(df, fig, "Steps", "Distance",
        init_params={}, route_func=get_data)
898964
def save_plot(cls, data, columns, plottype, fmt='json', **kwargs):
        
        cls._verify_export_dir()
        plot = {"use_visavis_type": plottype, "payload": {}}

        if isinstance(data, pd.DataFrame):
            iter_data = data.iterrows
            pointers = columns
        else:
            iter_data = lambda: enumerate(data)
            pointers = range(len(data[0]))

        if fmt == 'csv':
            fmt_export = os.path.join(cls.export_dir, cls._gen_basename() + ".csv")
            f_export = open(fmt_export, "w")
            f_export.write("%s\n" % ",".join(map(str, columns)))
            for _, row in iter_data():
                f_export.write("%s\n" % ",".join([str(row[i]) for i in pointers]))
            f_export.close()

        else:
            fmt_export = os.path.join(cls.export_dir, cls._gen_basename() + ".json")
            f_export = open(fmt_export, "w")

            if plottype == 'bar':

                plot["payload"] = {"x": [], "y": [], "xtitle": cls._get_title(columns[0]), "ytitle": cls._get_title(columns[1])}

                for _, row in iter_data():
                    plot["payload"]["x"].append(row[pointers[0]])
                    plot["payload"]["y"].append(row[pointers[1]])

            elif plottype == 'plot3d':

                plot["payload"]["points"] = {"x": [], "y": [], "z": [], "labels": []}
                plot["payload"]["meshes"] = []
                plot["payload"]["xtitle"] = cls._get_title(columns[0])
                plot["payload"]["ytitle"] = cls._get_title(columns[1])
                plot["payload"]["ztitle"] = cls._get_title(columns[2])
                recent_mesh = 0

                for _, row in iter_data():
                    plot["payload"]["points"]["x"].append(row[pointers[0]])
                    plot["payload"]["points"]["y"].append(row[pointers[1]])
                    plot["payload"]["points"]["z"].append(row[pointers[2]])
                    plot["payload"]["points"]["labels"].append(row[pointers[3]])

                    if row[4] != recent_mesh:
                        plot["payload"]["meshes"].append({"x": [], "y": [], "z": []})
                    recent_mesh = row[4]

                    if plot["payload"]["meshes"]:
                        plot["payload"]["meshes"][-1]["x"].append(row[pointers[0]])
                        plot["payload"]["meshes"][-1]["y"].append(row[pointers[1]])
                        plot["payload"]["meshes"][-1]["z"].append(row[pointers[2]])

            if kwargs:
                plot["payload"].update(kwargs)

            else: raise RuntimeError("\r\nError: %s is an unknown plot type" % plottype)

            f_export.write(json.dumps(plot, escape_forward_slashes=False, indent=4))
            f_export.close()

        return fmt_export
748580
private void initializePlot() {
    plot = new VisualizationPlot();
    { // Add a background element:
      CSSClass cls = new CSSClass(this, "background");
      final String bgcol = context.getStyleLibrary().getBackgroundColor(StyleLibrary.PAGE);
      cls.setStatement(SVGConstants.CSS_FILL_PROPERTY, bgcol);
      plot.addCSSClassOrLogError(cls);
      Element background = plot.svgElement(SVGConstants.SVG_RECT_TAG);
      background.setAttribute(SVGConstants.SVG_X_ATTRIBUTE, "0");
      background.setAttribute(SVGConstants.SVG_Y_ATTRIBUTE, "0");
      background.setAttribute(SVGConstants.SVG_WIDTH_ATTRIBUTE, "100%");
      background.setAttribute(SVGConstants.SVG_HEIGHT_ATTRIBUTE, "100%");
      SVGUtil.setCSSClass(background, cls.getName());
      // Don't export a white background:
      if("white".equals(bgcol)) {
        background.setAttribute(SVGPlot.NO_EXPORT_ATTRIBUTE, SVGPlot.NO_EXPORT_ATTRIBUTE);
      }
      plot.getRoot().appendChild(background);
    }
    { // setup the hover CSS classes.
      selcss = new CSSClass(this, "s");
      if(DEBUG_LAYOUT) {
        selcss.setStatement(SVGConstants.CSS_STROKE_PROPERTY, SVGConstants.CSS_RED_VALUE);
        selcss.setStatement(SVGConstants.CSS_STROKE_WIDTH_PROPERTY, .00001 * StyleLibrary.SCALE);
        selcss.setStatement(SVGConstants.CSS_STROKE_OPACITY_PROPERTY, "0.5");
      }
      selcss.setStatement(SVGConstants.CSS_FILL_PROPERTY, SVGConstants.CSS_RED_VALUE);
      selcss.setStatement(SVGConstants.CSS_FILL_OPACITY_PROPERTY, "0");
      selcss.setStatement(SVGConstants.CSS_CURSOR_PROPERTY, SVGConstants.CSS_POINTER_VALUE);
      plot.addCSSClassOrLogError(selcss);
      CSSClass hovcss = new CSSClass(this, "h");
      hovcss.setStatement(SVGConstants.CSS_FILL_OPACITY_PROPERTY, "0.25");
      plot.addCSSClassOrLogError(hovcss);
      // Hover listener.
      hoverer = new CSSHoverClass(hovcss.getName(), null, true);
    }

    // Disable Batik default interactions (zoom, rotate, etc.)
    if(single) {
      plot.setDisableInteractions(true);
    }
    SVGEffects.addShadowFilter(plot);
    SVGEffects.addLightGradient(plot);
  }
663921
function () {
		var options;
		seriesTypes.scatter.prototype.init.apply(this, arguments);

		options = this.options;
		this.pointRange = options.pointRange = pick(options.pointRange, options.colsize || 1); // #3758, prevent resetting in setData
		this.yAxis.axisPointRange = options.rowsize || 1; // general point range
	}
599844
def _make_plot_keywords(self, kwds, y):
        """"""
        # y is required for KdePlot
        kwds['bottom'] = self.bottom
        kwds['bins'] = self.bins
        return kwds
910168
def raster(times, indices, max_time=None, max_index=None, 
           x_label="Timestep", y_label="Index", **kwargs):
    """"""
    # set default size to 1
    if 's' not in kwargs:
        kwargs['s'] = 1
    scatter(times, indices, **kwargs)
    
    if max_time is None:
        max_time = max(times)
    if max_index is None:
        max_index = max(indices)
    axis((0, max_time, 0, max_index))
    if x_label is not None: xlabel(x_label)
    if y_label is not None: ylabel(y_label)
939616
def scatterplot(self, x, y, **kw):
        
        self.panel.scatterplot(x, y, **kw)