Exemple #1
0
def figure_to_svg(fig):
	tempFile = tempfile.NamedTemporaryFile(suffix='.svg.tmp', delete=False)
	canvas = FigureCanvasSVG(fig)
	canvas.print_svg(tempFile.name)
	svgImg = tempFile.read()
	os.remove(tempFile.name)
	return svgImg
Exemple #2
0
def get_graph_svg(guid):
    """Endpoint returning matplotlib svg graph
    ---
    parameters:
      - name: guid
        in: path
        required: true
        type: string
      - name: reference
        in: query
        type: string
        required: false
      - name: distance
        in: query
        type: string
        required: false
      - name: quality
        in: query
        type: string
        required: false
    responses:
      200:
        description:
    """
    reference = request.args.get('reference')
    if not reference: reference = cfg['default_reference']
    quality = request.args.get('quality')
    if not quality: quality = cfg['default_quality']
    cutoff = request.args.get('cutoff')
    if cutoff and int(cutoff) > 10:
        cutoff = 10
    if cutoff:
        (xs, ys) = graph3(guid, reference, quality, cfg['elephantwalkurl'],
                          int(cutoff))
    else:
        (xs, ys) = graph2(guid, reference, quality, cfg['elephantwalkurl'])
    if len(ys) == 0:
        slopes = []
    else:
        slopes = [0]
    print(xs)
    for n in range(len(xs)):
        if n == 0: continue
        slopes.append((ys[n] - ys[n - 1]) / (xs[n] - xs[n - 1]))
    fig = Figure(figsize=(12, 7), dpi=100)
    fig.suptitle("Sample: {0}, reference: {1}, quality: {2}, ew: {3}".format(
        guid, reference, quality, cfg['elephantwalkurl']))
    ax = fig.add_subplot(111)
    ax.xaxis.set_major_locator(MaxNLocator(integer=True))
    ax.plot(xs, ys, 'gx-', linewidth=1)
    ax.plot(xs, slopes, 'r-', linewidth=1)
    ax.set_xlabel("Distance")
    ax.set_ylabel("Neighbours")
    canvas = FigureCanvas(fig)
    svg_output = StringIO()
    canvas.print_svg(svg_output)
    response = make_response(svg_output.getvalue())
    response.headers['Content-Type'] = 'image/svg+xml'
    return response
Exemple #3
0
def malignancy_plot(age, tumour_size):

    # Scale age and tumour_size (note: output is numpy array)
    age_tumour_size = [[age] + [tumour_size]]
    age_tumour_size_scaled = malign_scaler.transform(age_tumour_size)

    # Create malignancy feature array
    malign_features = [age_tumour_size_scaled[0].tolist()]

    # Predict malignancy: 0 benign, 1 non-benign
    yscore_cal = malign_clf.predict_proba(malign_features)
    yscore_nonbenign = np.round(yscore_cal[0][1]*100, 1)
    ypred_cal = np.array(yscore_cal[:, 1] > 0.05, dtype=int)[0]  # threshold = 5%
    
    # Select title and title colour
    red = '#CC333F'
    blue = '#1693A7'
    if ypred_cal == 0:
        title = 'Benign'
        title_colour = blue
    elif ypred_cal == 1:
        title = 'Borderline malignancy / Malignant'
        title_colour = red

    ##### Plot Figure #####
    sns.set(font_scale=1.2)
    sns.set_style('white',{'axes.linewidth': 2.5, 'axes.edgecolor': '#D3D3D3'})

    # Create plot
    fig = Figure()
    ax = fig.add_subplot(1, 1, 1)

    # Draw plot
    sns.kdeplot(malign_valid_dist, color='orange', shade=True,
                gridsize=500, bw='silverman', ax=ax)
    ax.vlines(yscore_nonbenign, 0, 0.10, color='#D70E08', zorder=10)  # prediction
    txt = ax.text(yscore_nonbenign, 0.11, '   ' + str(yscore_nonbenign) + '%', color='#D70E08',
             zorder=10, horizontalalignment='center')  # prediction label
    txt.set_path_effects([path_effects.withStroke(linewidth=3, foreground='w')])  # label outline
    ax.vlines(5, 0, 0.25, color='#cccccc', zorder=10, linestyles='dashed')  # threshold (5%)
    ax.set_title('Prediction: ' + title, color=title_colour, fontsize=14)

    ax.set_ylabel('Probability density', labelpad=10)
    ax.set_xlabel('Probability (%)', labelpad=10)
    ax.set_xlim(0, 30)
    ax.set_ylim(0, 0.4)
    for axis in ['top','bottom','left','right']:
        ax.spines[axis].set_linewidth(2)
    sns.despine(ax=ax)
    fig.set_tight_layout(True)

    # Write plot to SVG
    canvas = FigureCanvas(fig)
    output = BytesIO()
    # canvas.print_svg('test.svg')  # For testing fig output locally
    canvas.print_svg(output)
    response = make_response(output.getvalue())
    response.mimetype = 'image/svg+xml'
    return response
Exemple #4
0
  def canvas(self):
    type = self.get("imageType", "png")
    fig = Figure()
    if type == "png":
      canvas = FigureCanvasAgg(fig)
      (self.file, self.filename) = mkstemp(".%s" % type)
    elif type == "svg":
      canvas = FigureCanvasSVG(fig)
      (self.file, self.filename) = mkstemp(".%s" % type)
    elif type == "pdf":
      canvas = FigureCanvasPdf(fig)
      (self.file, self.filename) = mkstemp(".%s" % type)
    elif type == "ps" or type == "eps":
      canvas = FigureCanvasPS(fig)
      (self.file, self.filename) = mkstemp(".%s" % type)
    else:
      raise "Invalid render target requested"

    # Set basic figure parameters
    dpi = float(self.get('dpi'))
    (w, h) = (float(self.get('width')), float(self.get('height')))
    (win, hin) = (w/dpi, h/dpi)
    fig.set_size_inches(win, hin)
    fig.set_dpi(dpi)
    fig.set_facecolor('white')
    return (fig, canvas, w, h)
Exemple #5
0
def equations_plot_svg(f, g):
    print(f, g)
    x = np.linspace(-10, 10, 1000000)
    y1 = ne.evaluate(f)
    y2 = ne.evaluate(g)

    chart, curve = plt.subplots()
    # Disegno la curva
    curve.plot(x, y1, 'blue', linewidth=2)
    curve.plot(x, y2, 'green', linewidth=2)

    intersetions_points = []
    idx = np.argwhere(np.diff(np.sign(y1 - y2))).flatten()

    for i in idx:
        print(y2[i])
        if not np.isnan(y1[i]) and not np.isnan(y2[i]):
            intersetions_points.append(np.around(x[i], decimals=2))
            plt.plot(x[i], y1[i], 'ro')

    intesetion_point = '; '.join([str(elem) for elem in intersetions_points])
    chart.text(.1, .9, f'Risultato: {intesetion_point}')
    output = io.BytesIO()
    FigureCanvasSVG(chart).print_svg(output)
    return Response(output.getvalue(), mimetype="image/svg+xml")
def _test_determinism_save(filename, usetex):
    # This function is mostly copy&paste from "def test_visibility"
    # To require no GUI, we use Figure and FigureCanvasSVG
    # instead of plt.figure and fig.savefig
    from matplotlib.figure import Figure
    from matplotlib.backends.backend_svg import FigureCanvasSVG
    from matplotlib import rc
    rc('svg', hashsalt='asdf')
    rc('text', usetex=usetex)

    fig = Figure()
    ax = fig.add_subplot(111)

    x = np.linspace(0, 4 * np.pi, 50)
    y = np.sin(x)
    yerr = np.ones_like(y)

    a, b, c = ax.errorbar(x, y, yerr=yerr, fmt='ko')
    for artist in b:
        artist.set_visible(False)
    ax.set_title('A string $1+2+\\sigma$')
    ax.set_xlabel('A string $1+2+\\sigma$')
    ax.set_ylabel('A string $1+2+\\sigma$')

    FigureCanvasSVG(fig).print_svg(filename)
Exemple #7
0
 def fugure_to_image(self, fig: FigureCanvasSVG, svg: bool) -> io.BytesIO:
     output = io.BytesIO()
     if svg:
         FigureCanvasSVG(fig).print_svg(output)
     else:
         FigureCanvasAgg(fig).print_png(output)
     return output
def plot_pie(parts=5):
    import matplotlib.pyplot as plt
    from utils.rndm import randomword

    # Pie chart, where the slices will be ordered and plotted counter-clockwise:
    labels = [randomword(6) for i in range(parts)]
    sizes = [random.randint(1, 101) for i in range(parts)]  #15, 30, 45, 10]
    explode = [
        0
    ] * parts  #(0, 0.1, 0, 0)  # only "explode" the 2nd slice (i.e. 'Hogs')
    explode[random.randint(0, parts)] = 0.1

    fig1, ax1 = plt.subplots()
    ax1.pie(sizes,
            explode=explode,
            labels=labels,
            autopct='%1.1f%%',
            shadow=True,
            startangle=90)
    ax1.axis(
        'equal')  # Equal aspect ratio ensures that pie is drawn as a circle.

    output = io.BytesIO()
    FigureCanvasSVG(fig1).print_svg(output)
    return Response(output.getvalue(), mimetype="image/svg+xml")
Exemple #9
0
def cli():
    args = get_args()

    fig = matplotlib.figure.Figure(figsize=(args.dimensions[0] / 2.54,
                                            args.dimensions[1] / 2.54))
    ax = fig.add_subplot(1, 1, 1, frameon=False)
    if args.svg:
        FigureCanvasSVG(fig)
    else:
        FigureCanvasAgg(fig)

    table = pandas.read_table(args.table, sep=" ")
    args.table.close()
    spider(args.algorithm,
           args.problem,
           args.statistic,
           args.metric,
           table,
           ax,
           draw_ci=args.draw_ci)

    fn = filename(args.algorithm, args.problem, args.statistic, args.metric)
    if args.svg:
        fn = fn + ".svg"
    else:
        fn = fn + ".png"
    fig.savefig(os.path.join(args.output_dir, fn))
def main(restaurant, order, show_count, token):
    restaurant_id = restaurant
    fig = get_statistics_per_restaurant(restaurant_id, Orders.all(token),
                                        order, int(show_count))
    output = io.BytesIO()
    FigureCanvasSVG(fig).print_svg(output)
    return output.getvalue()
Exemple #11
0
def plot_png(id):
    response = requests.get(APIurl + 'getDataLatest?id={}&nVals={}'.format(id,10))
    data = pd.read_json(response.text)
    fig, output = createPlot(data)

    FigureCanvasSVG(fig).print_svg(output)
    return Response(output.getvalue(), mimetype="image/svg+xml")
def polar_pie(parts):
    """
    =======================
    Pie chart on polar axis
    =======================

    Demo of bar plot on a polar axis.
    """
    import numpy as np
    import matplotlib.pyplot as plt

    fig = plt.figure()
    # Compute pie slices
    N = 20
    theta = np.linspace(0.0, 2 * np.pi, N, endpoint=False)
    radii = 10 * np.random.rand(N)
    width = np.pi / 4 * np.random.rand(N)

    ax = plt.subplot(111, projection='polar')
    bars = ax.bar(theta, radii, width=width, bottom=0.0)

    # Use custom colors and opacity
    for r, bar in zip(radii, bars):
        bar.set_facecolor(plt.cm.viridis(r / 10.))
        bar.set_alpha(0.5)
    #
    # plt.savefig('foo.png')
    # plt.close()

    fig.savefig('temp.png', dpi=fig.dpi)
    output = io.BytesIO()
    FigureCanvasSVG(fig).print_svg(output)
    return Response(output.getvalue(), mimetype="image/svg+xml")
Exemple #13
0
def build_graph_multiproc(chunk,lstOfwavelengths,pltcodeWithSuffix):
    global lstOfPlots
    with cx_Oracle.connect(user,passwrd,dsn_tns) as conn:
        cr = conn.cursor()
        for i, wid in chunk:
            img = io.BytesIO()
            fig = Figure(figsize=(0.6,0.6))
            axis = fig.add_subplot(1,1,1)
            absVals = getAllWellVals(cr,tableName_abs,pltcodeWithSuffix,wid)
            if int(pltcodeWithSuffix[2:4]) < 18: 
                lstOfwavelengths = getLstOfwavelengths('WELL_ABSORBANCE',pltcodeWithSuffix)

            axis.plot(lstOfwavelengths,absVals)
            axis.set_title(f'{wid}',fontsize=9)
            axis.title.set_position([.5, .6])
            axis.tick_params(
                    which='both',
                    bottom=False,
                    left=False,
                    labelbottom=False,
                    labelleft=False)
            FigureCanvasSVG(fig).print_svg(img)
            result = img.getvalue()
            try:
                lstOfPlots[i] = (i,result)
            except IndexError:
                lstOfPlots.append((i,result))
Exemple #14
0
def plot_svg(num_x_points=50):
    fig = Figure()
    axis = fig.add_subplot(1, 1, 1)
    x_points = range(num_x_points)
    axis.plot(x_points, [random.randint(1, 30) for x in x_points])
    output = io.BytesIO()
    FigureCanvasSVG(fig).print_svg(output)
    return Response(output.getvalue(), mimetype='image/svg+xml')
Exemple #15
0
def plot_heatmap(df):
    #df = generate_df()
    fig = Figure()
    axes = fig.add_subplot(1, 1, 1)
    axes.imshow(df)

    output = io.BytesIO()
    FigureCanvasSVG(fig).print_svg(output)
    return Response(output.getvalue(), mimetype="image/svg+xml")
Exemple #16
0
def draw_custom_graph(user_agents):
    plot_x_y = []

    # requests = log_parser.get_log_dicts(user_agent = r'SiteSucker.*')
    for user_agent in user_agents:
        requests = logger.get_log_dicts(user_agent=user_agent)
        first_date = None
        x = []
        y = []
        for index, request in enumerate(requests):
            if index is not 0:
                x.append(time_delta(request['datetime'], first_date))
            else:
                first_date = request['datetime']
                x.append(0)
            y.append(index)
        plot_x_y.append({
            'x': x,
            'y': y
        })

    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)

    current_index = 0
    for xy in plot_x_y:
        # todo: Use different color (not only random) and add the ability to choose multiple user_agent.
        ax.plot(
            xy['x'], xy['y'],
            color=graph_colors[current_index % len(graph_colors)],
            label=user_agents[current_index]
        )
        ax.legend(framealpha=0.5, loc=4, prop={'size': 8})
        current_index += 1

    plt.xlabel('Delta Time (seconds)')
    plt.ylabel('Number of requests')

    ax.xaxis.set_major_formatter(formatter)

    output = StringIO.StringIO()
    canvas = FigureCanvas(fig)
    canvas.print_svg(output)
    return output
Exemple #17
0
def plotdists(dists, labelmap=None, bins=20, alpha=0.5):
    svg = StringIO()
    fig = figure.Figure(figsize=PLOTSIZE)
    ax = fig.add_subplot(1, 1, 1)
    if labelmap is None:
        labelmap = {key: key for key in dists.keys()}
    for key, dist in dists.items():
        ax.hist(dist, bins=bins, alpha=alpha, label=labelmap[key])
    ax.legend()
    FigureCanvasSVG(fig).print_svg(svg)
    svg.seek(0)
    return svg.read()
Exemple #18
0
def plot_emes01g(V, f):
    fig = Figure()
    fig.set_size_inches(15, 12)
    Torq, slip, Nr = torque_vs_slip(V, f)
    axis = fig.add_subplot(2, 1, 1)
    axis.xlabel = 'Nr'
    axis.ylabel = 'Torque'
    axis.plot(Nr, Torq, c='red', linewidth=4)
    axis.grid()

    output = io.BytesIO()
    FigureCanvasSVG(fig).print_svg(output)
    return Response(output.getvalue(), mimetype="image/svg+xml")
Exemple #19
0
def plot_hvg(R, C):
    C *= 1e-6
    fig = Figure()
    f, Gain, phase = high_pass_filter(R, C)
    axis = fig.add_subplot(2, 1, 1)
    axis.semilogx(f, Gain)

    axis = fig.add_subplot(2, 1, 2)
    axis.semilogx(f, phase)

    output = io.BytesIO()
    FigureCanvasSVG(fig).print_svg(output)
    return Response(output.getvalue(), mimetype="image/svg+xml")
Exemple #20
0
def total_dist_svg():
    # https://gist.github.com/illume/1f19a2cf9f26425b1761b63d9506331f
    fig = Figure(tight_layout=True)
    ax = fig.add_subplot(1, 1, 1)
    x = []
    y = []
    a_file = session["a_file"]
    with open(a_file, 'rb') as af:
        acts = pickle.load(af)
    for i in range(len(acts)-1, -1, -1):
        x.append(mdates.date2num([acts[i]['start_date']])[0])
        dist = meters_to_miles(acts[i]['distance'])
        if len(y) > 0:
            y.append(y[-1] + dist)
        else:
            y.append(dist)
    strava_orange = '#fc4c02'
    ax.plot(x, y, color=strava_orange, marker='.')
    ax.fill_between(x, y, color=strava_orange, alpha=0.5)
    ax.set_xlabel('Date')
    date_formatter = mdates.DateFormatter('%Y-%m-%d')
    lower_lim_x = x[0]
    upper_lim_x = x[-1]
    x_buffer = 0.05
    width = upper_lim_x - lower_lim_x
    lower_lim_x -= x_buffer * width
    upper_lim_x += x_buffer * width
    ax.set_xlim(lower_lim_x, upper_lim_x)
    x_ticks = ax.get_xticks().tolist()
    ax.xaxis.set_major_locator(mticker.FixedLocator(x_ticks))
    ax.set_xticklabels(x_ticks, rotation=45)
    ax.xaxis.set_major_formatter(date_formatter)
    ax.set_ylabel('Distance (Miles)')
    y_buffer = 0.1
    top_lim_y = (1 + y_buffer) * y[-1]
    ax.set_ylim(0, top_lim_y)

    gray = "#808080"
    ax.plot([lower_lim_x, upper_lim_x], [y[-1], y[-1]], color=gray,
        linestyle='--', alpha=0.5)
    text_gap_x = 1
    text_gap_y = 1
    pt = (lower_lim_x, y[-1])
    figure_pt = (pt[0] + text_gap_x, pt[1] + text_gap_y)
    ax.annotate(f"{round(y[-1], 1)} Miles", pt, xytext=figure_pt)

    ax.set_title('Total Distance')

    output = io.BytesIO()
    FigureCanvasSVG(fig).print_svg(output)
    return Response(output.getvalue(), mimetype="image/svg+xml")
Exemple #21
0
    def drawPlot2(self):
        self.axt.clear()
        X = linspace(self.X_Mmin, self.X_Mmax, self.N)
        Y = X
        self.B = (self.k * self.b * X) / (2.0 * self.f_2)
        self.A = (self.k * self.h * Y) / (2.0 * self.f_2)
        BB, HH = meshgrid(self.B, self.A)
        self.I = ((sin(BB) / BB)**2) * (sin(HH) / (HH))**2
        self.axt.plot_surface(BB, HH, self.I, cmap='viridis', edgecolor='none')
        self.axt.view_init(10, 45)

        output = io.BytesIO()
        FigureCanvasSVG(self.fig3).print_svg(output)
        return output.getvalue()
def plot_svg(subject):
    signal = np.loadtxt('uploads/'+subject+'.csv')
    signal = signal[:10000]

    _, _, r_peaks, _, _, _, _ = ecg.ecg(
        signal=signal, sampling_rate=500, show=False)

    fig = Figure(figsize=(12, 4))
    axis = fig.add_subplot(1, 1, 1)
    axis.plot(signal)
    axis.plot(r_peaks, signal[r_peaks], 'r*')
    axis.grid()

    output = io.BytesIO()
    FigureCanvasSVG(fig).print_svg(output)
    return Response(output.getvalue(), mimetype="image/svg+xml")
Exemple #23
0
def plotOhm():
    a = []
    b = []
    reco = {}
    for reco in ohm.allrecord:
        b.append(reco['voltage'])
        a.append(reco['current'])

    figure = plt.figure(figsize=(10, 5))
    plt.xlabel("Current in ampere")
    plt.ylabel("Voltage (volt)")
    plt.plot(a, b, linestyle='--', marker='o', color='b')
    plt.grid()

    output = io.BytesIO()
    FigureCanvasSVG(figure).print_svg(output)
    return Response(output.getvalue(), mimetype="image/svg+xml")
Exemple #24
0
 def drawPlot(self):
     self.axs.clear()
     self.i = (1 / self.n**2) * ((sin(self.Bb) / self.Bb)**2) * (
         sin(self.n * self.Aa) / sin(self.Aa))**2
     self.sinc = (sin(self.Bb) / self.Bb)**2
     self.axs.plot(self.x,
                   self.i,
                   '-k',
                   self.x,
                   self.sinc,
                   ':b',
                   linewidth=2)
     self.axs.set_xlim(self.X_Mmin, self.X_Mmax)
     self.axs.set_xlabel('X (m)', fontsize=12, fontweight='bold')
     self.axs.set_ylabel('I(X,Y)/I_0', fontsize=12, fontweight='bold')
     output = io.BytesIO()
     FigureCanvasSVG(self.fig2).print_svg(output)
     return output.getvalue()
Exemple #25
0
def plot_svg():
    """ renders the plot on the fly.
  """
    datapoints_dict = session["datapoints_dict"]
    fig = Figure()
    axis = fig.add_subplot(1, 1, 1)
    lists = sorted(datapoints_dict.items())
    x, y = zip(*lists)
    ts = []
    for t in x:
        print("#######", t)
        ts.append(utils.get_time_str_from_epoch(float(t)))
    print(x)
    print(ts)
    axis.plot(ts, y)

    output = io.BytesIO()
    FigureCanvasSVG(fig).print_svg(output)
    return Response(output.getvalue(), mimetype="image/svg+xml")
Exemple #26
0
 def plot(self, gridspec=None, figsize=(11, 8.5), filetype="pdf"):
     if gridspec is None:
         gridspec = dict(left=0.05, right=0.94, wspace=0.05)
     nplots = len(self.plotspecs)
     fig = mpl.figure.Figure(figsize=figsize)
     if filetype.lower() == "pdf":
         FigureCanvasPdf(fig)
     elif filetype.lower() == "svg":
         FigureCanvasSVG(fig)
     else:
         raise ValueError("Unknown filetype: %s" % filetype)
     if self.title:
         fig.suptitle(self.title)
     gs = GridSpec(nplots, 1)
     gs.update(**gridspec)
     for i in xrange(0, nplots):
         self.plotspecs[i].plot(fig, gs, i)
     fig.set_size_inches(figsize)
     fig.savefig(self.filename + "." + filetype,
                 format=filetype.lower(), facecolor="none")
Exemple #27
0
def plot_graph():

    # load f1 scores from session into local list
    score_f1 = score = session["f1_scores"]

    # create matplotlib graph showing f1 scores
    fig = Figure()
    axis = fig.add_subplot(1, 1, 1)
    x_points = range(len(score_f1))
    axis.plot(x_points, [score_f1[x] for x in x_points])
    axis.set_title('Federated Model - F1 Score History')
    axis.set_ylabel('F1 Score')
    axis.set_xlabel('Epoch')

    # initialise raw output for rendering graph as svg data
    output = io.BytesIO()
    FigureCanvasSVG(fig).print_svg(output)

    # returns svg formatted graph
    return Response(output.getvalue(), mimetype="image/svg+xml")
def definite_intergrals_plot_svg(fx, a, b):
    a, b = int(a), int(b)
    PRECISION = (b - a) * 20
    x = np.linspace(a, b, PRECISION)
    y = ne.evaluate(fx)

    chart, curve = plt.subplots()
    # Disegno la curva
    curve.plot(x, y, 'red', linewidth=2)
    underlying_area = 0
    for index in range(0, len(x) - 1):
        deltax = x[index + 1] - x[index]
        # Calcolo l'area del rettangolo piccolo
        if not np.isnan(y[index]) and not np.isnan(y[index + 1]):
            rectangle_min = plt.Rectangle((x[index], 0),
                                          deltax,
                                          y[index],
                                          alpha=.2,
                                          fc='green',
                                          ec="black")
            area_min = rectangle_min.get_height() * rectangle_min.get_width()
            # Calcolo l'area del rettangolo grande
            rectangle_max = plt.Rectangle((x[index], 0),
                                          deltax,
                                          y[index + 1],
                                          alpha=.1,
                                          fc='blue',
                                          ec="black")
            area_max = rectangle_max.get_height() * rectangle_max.get_width()
            # Disegno i due rettangoli sul grafico
            curve.add_patch(rectangle_min)
            curve.add_patch(rectangle_max)
            # Aggiungo la media dei due rettangoli all'area totale
            underlying_area += np.mean([area_min, area_max])

    # Mostro il grafico e stampo il risultato
    chart.text(.1, .9, f'Risultato: {np.around(underlying_area, decimals=2)}')
    output = io.BytesIO()
    FigureCanvasSVG(chart).print_svg(output)
    return Response(output.getvalue(), mimetype="image/svg+xml")
Exemple #29
0
def plot_gating_signal(alpha):
    t = 0
    t_array = np.arange(0, 8, 0.01)
    V = 0
    Vt = []
    for t in np.arange(0, 8, 0.01):
        if (t - int(t)) <= (alpha / 100):
            Vt.append(600)
        else:
            Vt.append(0)
    figure = plt.figure(figsize=(10, 5))

    plt.axis([0, 8, 0, 800])
    plt.xlabel("time (micro-seconds)", fontsize=14)
    plt.ylabel("Terminal voltage of Motor (Vt)", fontsize=14)
    plt.plot(t_array, Vt, color='b')
    plt.text(3.4,
             750,
             'Chopping Frequency (f) = 1 Mega-Hertz (MHz)',
             fontsize=12,
             fontweight='bold',
             bbox={
                 'facecolor': 'yellow',
                 'alpha': 0.5,
                 'pad': 4
             })
    plt.text(3.4,
             680,
             'T = (1/f) = Toff + Ton = 1 micro-second',
             fontsize=12,
             fontweight='bold',
             bbox={
                 'facecolor': 'yellow',
                 'alpha': 0.5,
                 'pad': 4
             })
    plt.grid()
    output = io.BytesIO()
    FigureCanvasSVG(figure).print_svg(output)
    return Response(output.getvalue(), mimetype="image/svg+xml")
Exemple #30
0
def draw_graph_rev2(y, G, edge_labs, pos, labs, ax=None):
    """ Function to draw the graph.

    INPUTS
    ======
    y : ADnum

    OUTPUTS
    =======
    A plot of the graph
    """
    fig = Figure()
    fig.set_size_inches(9, 6)
    #G = gen_graph(y)
    G = G.reverse()
    #edge_labs = nx.get_edge_attributes(G, 'label')
    #pos = nx.spring_layout(G)
    #labs = get_labels(y)
    #labs = get_labels_rev(y)
    ax = fig.add_subplot(1, 1, 1)
    nx.draw_networkx(G,
                     pos,
                     labels=labs,
                     node_color=get_colors(G, y),
                     node_size=get_sizes(G, y, labs),
                     font_color='white',
                     ax=ax)
    nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labs, ax=ax)
    ax.axis('off')
    mag_patch = mpatches.Patch(color='magenta', label='input')
    red_patch = mpatches.Patch(color='red', label='intermediate')
    blue_patch = mpatches.Patch(color='blue', label='constant')
    green_patch = mpatches.Patch(color='green', label='output')
    ax.legend(handles=[mag_patch, red_patch, blue_patch, green_patch])
    #plt.show()
    #return fig
    output = io.BytesIO()
    FigureCanvasSVG(fig).print_svg(output)
    return output
Exemple #31
0
from matplotlib.backends.backend_svg import FigureCanvasSVG as FigureCanvas

# from matplotlib.backends.backend_cairo import FigureCanvasCairo as FigureCanvas
from matplotlib.figure import Figure


xlim = [0, 10.0]
YMAX = 240.00
ylim = [0, YMAX]
fig = Figure()
canvas = FigureCanvas(fig)
# xticks = [ 1,2,3,4,5,6,7,8  ]
ax = fig.add_subplot(111, xlim=xlim, ylim=ylim, xticks=range(10))
data = [[False, False], [1, 200], [4, 100], [6, 120]]
# ax.plot(data)
D = dict(data)

ax.stem(D.keys(), D.values(), "-.")

ax.set_title("hi mom")
ax.grid(True)
ax.set_xlabel("time")
ax.set_ylabel("glucose")
canvas.print_figure("test")


#####
# EOF
Exemple #32
0
# using the matplotlib API - look, maw, no matlab!
from matplotlib.backends.backend_svg import FigureCanvasSVG
from matplotlib.figure import Figure
fig = Figure()
ax = fig.add_subplot(211)
ax.plot([1,2,3])
canvas = FigureCanvasSVG(fig)
canvas.print_figure('myfile.svg')