Beispiel #1
0
def hi_res():
    try:
        # Try vector graphic first
        from IPython.display import set_matplotlib_formats
        set_matplotlib_formats( 'svg')
    except:
        # if that fails, at least raise the resolution of the plots. 
        import matplotlib as mpl
        mpl.rcParams['savefig.dpi'] = 200
Beispiel #2
0
    def compute_output(self, output_module, configuration=None):
        from IPython.display import set_matplotlib_formats
        from IPython.core.display import display

        set_matplotlib_formats('png')

        # TODO: use size from configuration
        fig = output_module.get_input('value')
        display(fig.figInstance)
Beispiel #3
0
def semilogy(x_vals, y_vals, x_label, y_label, x2_vals=None, y2_vals=None,
             legend=None, figsize=(3.5, 2.5)):
    """Plot x and log(y)."""
    plt.rcParams['figure.figsize'] = figsize
    set_matplotlib_formats('retina')
    plt.xlabel(x_label)
    plt.ylabel(y_label)
    plt.semilogy(x_vals, y_vals)
    if x2_vals and y2_vals:
        plt.semilogy(x2_vals, y2_vals)
        plt.legend(legend)
    plt.show()
def init_pyplot():
    from IPython.display import set_matplotlib_formats
    set_matplotlib_formats('pdf', 'png')
    plt.rcParams['savefig.dpi'] = 75
    plt.rcParams['figure.autolayout'] = False
    plt.rcParams['figure.figsize'] = 10, 6
    plt.rcParams['axes.labelsize'] = 18
    plt.rcParams['axes.titlesize'] = 20
    plt.rcParams['font.size'] = 12
    plt.rcParams['lines.linewidth'] = 2.0
    plt.rcParams['lines.markersize'] = 8
    plt.rcParams['legend.fontsize'] = 10
    plt.rcParams['text.usetex'] = False
    plt.rcParams['font.family'] = "sans serif"
    plt.rcParams['font.serif'] = "cm"
    plt.rcParams['text.latex.preamble'] = r"\usepackage{subdepth}, \usepackage{type1cm}"
Beispiel #5
0
def metagPlotspdf(SRAList, Names, Params):
    #
    #
    # ---------- Output graphics quality setings -------------
    #
    #   modify according your needs and system setup
    #   OSX users safest is to uncomment all
    #
    #
    from IPython.display import set_matplotlib_formats
    set_matplotlib_formats('pdf', 'svg')
    # Using laTeX to set Helvetica as default font
    # from matplotlib import rc
    # rc('font', **{'family': 'sans-serif', 'sans-serif': ['Helvetica']})
    # rc('text', usetex=True)
    # -------------------------------------------------------
    #
    # using pandas, matplotlib, seaborn, numpy
    makeDirectory("8-MetagPlot")
    sns.set_style("white")  # seaborn_aesthetic
    sns.set_context("paper")  # seaborn_aesthetic

    Span = int(Params["MetagSpan"])
    Mapping = Params["Mapping"]
    dataNorm = Params["Normalised"]  # Mapping 5 or 3 prime end
    rlrange = Params["ReadLenMiN"] + "-" + Params[
        "ReadLenMaX"]  # readlength range -> filename
    readLen_l = [
        str(i) for i in range(int(Params["ReadLenMiN"]),
                              int(Params["ReadLenMaX"]) + 1)
    ] + ["sum"]

    # colors for plot
    colors = {
        '25': 'fuchsia',
        '26': 'blueviolet',
        '27': 'darkblue',
        '28': 'b',
        '29': 'r',
        '30': 'salmon',
        '31': 'orange',
        '32': 'olive',
        '33': 'g',
        '34': 'tan',
        '35': 'y',
        'sum': 'brown'
    }

    for iN in Names:
        for iX in ["Start", "Stop"]:
            infile = "7-MetagTbl/" + iN + "_" + iX + ".txt"
            outfig = "8-MetagPlot/" + iN + "_" + iX + ".pdf"

            outfig_title = "{} {} {}' mapping".format(iN.replace('_', '-'), iX,
                                                      Mapping)
            legend_location = 'upper right' if iX == 'Stop' else 'upper left'

            if os.path.isfile(infile):  # infile exits

                w = 8  # figure width
                h = 1.2 * len(readLen_l)  # figure height

                fig, axes = plt.subplots(nrows=len(readLen_l), figsize=(w, h))

                fig.suptitle(outfig_title, y=0.9, fontsize=12)
                df = pd.read_csv(infile, index_col=0, sep='\t')
                df.set_index("rel_Pos", inplace=True)

                # Adjust plot for mapping and Start/Stop

                if (Mapping == '5') & (iX == "Start"):
                    df = dfTrimmiX5(df,
                                    Span,
                                    iX,
                                    inside_gene=39,
                                    outside_gene=21)
                elif (Mapping == '5') & (iX == "Stop"):
                    df = dfTrimmiX5(df,
                                    Span,
                                    iX,
                                    inside_gene=60,
                                    outside_gene=3)
                elif (Mapping == '3') & (iX == "Start"):
                    df = dfTrimmiX5(df,
                                    Span,
                                    iX,
                                    inside_gene=60,
                                    outside_gene=3)
                elif (Mapping == '3') & (iX == "Stop"):
                    df = dfTrimmiX5(df,
                                    Span,
                                    iX,
                                    inside_gene=39,
                                    outside_gene=30)
                else:
                    pass

                for i, readLen in enumerate(readLen_l):
                    a = 0.6
                    colors = colorsCheck(colors, readLen)
                    x = df.index
                    y = list(df.loc[:, readLen])
                    axes[i].bar(x, y, color=colors[readLen], alpha=a)
                    axes[i].legend([readLen], loc=legend_location)

                    # colors for guide lines; adjust for beg and end for 5pr
                    b, e = (df.index.min(), df.index.max())

                    if Mapping == '5':
                        for k in list(range(b, e + 1, 3)):
                            color = 'gray'
                            if k == -12:
                                color = 'g'
                                a = 0.5
                            elif k == 0:
                                color = 'r'
                                a = 0.4
                            elif k < 0:
                                color = 'gray'
                                a = 0.2
                            else:
                                color = 'gray'
                                a = 0.2
                            # add line after each 3 nt
                            axes[i].axvline(x=k,
                                            linewidth=1,
                                            alpha=a,
                                            color=color)

                    elif Mapping == '3':
                        for k in list(range(b, e + 1, 3)):
                            color = 'gray'
                            if k == 12:
                                color = 'g'
                                a = 0.5
                            elif k == 0:
                                color = 'r'
                                a = 0.4
                            elif k < 0:
                                color = 'gray'
                                a = 0.2
                            else:
                                color = 'gray'
                                a = 0.2
                            # add line after each 3 nt
                            axes[i].axvline(x=k,
                                            linewidth=1,
                                            alpha=a,
                                            color=color)
                    else:
                        # any other type of mapping
                        pass

                    axes[i].set_ylabel(Params["Normalised"])

                sns.despine()  # seaborn_aesthetic
                plt.tight_layout()
                fig.savefig(outfig, format='pdf', dpi=300, bbox_inches='tight')
                print("{}".format(outfig))
            else:
                print("Missing InFile -> {}".format(infile))
def set_figsize(figsize=(3.5, 2.5)):
    """Set matplotlib figure size."""
    set_matplotlib_formats('retina')
    plt.rcParams['figure.figsize'] = figsize
Beispiel #7
0
def use_svg_display():
    display.set_matplotlib_formats("svg")
Beispiel #8
0
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from cycler import cycler
from IPython.display import display, set_matplotlib_formats, HTML

display(
    HTML(data="""
<style>
    div#notebook-container    { width: 95%; }
    div#menubar-container     { width: 65%; }
    div#maintoolbar-container { width: 99%; }
</style>
"""))

set_matplotlib_formats('pdf', 'png')
plt.rcParams['savefig.dpi'] = 300
plt.rcParams['image.cmap'] = "viridis"
plt.rcParams['image.interpolation'] = "none"
plt.rcParams['savefig.bbox'] = "tight"
plt.rcParams['lines.linewidth'] = 2
plt.rcParams['legend.numpoints'] = 1

np.set_printoptions(precision=3, suppress=True)

pd.set_option("display.max_columns", 8)
pd.set_option('precision', 2)

__all__ = ['np', 'display', 'plt', 'pd']
def use_svg_display():
    """Use svg format to display plot in jupyter"""
    display.set_matplotlib_formats('svg')
Beispiel #10
0
import numpy as np
import cv2
import matplotlib.pyplot as plt
from IPython.display import set_matplotlib_formats
from collections import Counter

set_matplotlib_formats('svg')


def show_video(video):
    array = []

    while video.isOpened():
        ret, frame = video.read()

        try:
            gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        except cv2.error:
            print("End of the video")
            break

        blur = cv2.medianBlur(gray, 5)
        cimg = cv2.cvtColor(blur, cv2.COLOR_GRAY2BGR)

        roi, gray_roi = crop_video(cimg, gray)

        if ret:

            circles = find_circles(gray_roi)

            if circles is None:
Beispiel #11
0
def use_svg_display():
    # Display in vector graphics
    display.set_matplotlib_formats('svg')
Beispiel #12
0
import mxnet as mx
from mxnet import nd
import numpy as np
from matplotlib import pyplot as plt
from IPython import display
import random
import math

display.set_matplotlib_formats('svg')

probabilities = nd.ones(6) / 6
rand = nd.random.multinomial(probabilities, shape=(5, 10))
print(probabilities)
print(rand)

total = 1000
rolls = nd.random.multinomial(probabilities, shape=(total))
counts = nd.zeros((6, total))
totals = nd.zeros(6)
for i, roll in enumerate(rolls):
    totals[int(roll.asscalar())] += 1
    counts[:, i] = totals

print(totals / total)
print(counts)

x = nd.arange(total).reshape((1, total)) + 1
estimates = counts / x
print(estimates[:, 0])
print(estimates[:, 1])
print(estimates[:, 2])
Beispiel #13
0
import coco_preprocess
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import set_matplotlib_formats
set_matplotlib_formats('jpg')
from PIL import Image, ImageDraw

#%% visualizing queries and retrievals

def show_image(imgID, dataSet, coco):
    img_pil = get_img_pil(imgID, dataSet, coco)
    plt.axis('off')
    plt.imshow(img_pil)
    plt.show()

def get_img_pil(imgID, dataSet, coco):
    img = coco.loadImgs([imgID])[0] # make sure image ID exists in the dataset given to you.
    return Image.open('%s/%s/%s'%(coco_preprocess.dataDir, dataSet, img['file_name'])) # make sure data dir is correct

def plot_dev_box(pt_idx):
    imgID = box_img_ids_dev[pt_idx]
    img_pil = get_img_pil(imgID, 'val2014_2', coco_dev)
    x, y, w, h = bboxes_dev[pt_idx]
    draw = ImageDraw.Draw(img_pil)
    draw.rectangle(((x, y, x+w, y+h)), fill=None, outline=(255, 255, 51)) #RGB
    plt.imshow(img_pil)
    plt.show

def plot_train_box(pt_idx):
    imgID = box_img_ids[pt_idx]
    img_pil = get_img_pil(imgID, 'train2014_2', coco_train)
Beispiel #14
0
def use_jpg_display():
    display.set_matplotlib_formats('jpg')
Beispiel #15
0
def user_svg_display():
    display.set_matplotlib_formats('svg')
Beispiel #16
0
# load packages
import pandas as pd
import numpy as np
# import pandas_datareader as pdr
import seaborn as sns
from matplotlib import pyplot as plt
# not needed, only to prettify the plots.
import matplotlib
from IPython.display import set_matplotlib_formats
%matplotlib inline

# ploting setup
plt.style.use(['seaborn-white', 'seaborn-paper'])
matplotlib.rc('font', family='Times New Roman', size=15)
set_matplotlib_formats('png', 'png', quality=90)
plt.rcParams['savefig.dpi'] = 150
plt.rcParams['figure.autolayout'] = False
plt.rcParams['figure.figsize'] = 8, 5
plt.rcParams['axes.labelsize'] = 10
plt.rcParams['axes.titlesize'] = 15
plt.rcParams['font.size'] = 12
plt.rcParams['lines.linewidth'] = 1.0
plt.rcParams['lines.markersize'] = 8
plt.rcParams['legend.fontsize'] = 12
plt.rcParams['ytick.labelsize'] = 11
plt.rcParams['xtick.labelsize'] = 11
plt.rcParams['font.family'] = 'Times New Roman'
plt.rcParams['font.serif'] = 'cm'
plt.rcParams['axes.grid'] = True
kw_save = dict(bbox_iches='tight', transparent=True)
Beispiel #17
0
    def set_cloud(self):
        matplotlib.rc('font',family = 'Malgun Gothic')

        set_matplotlib_formats('retina')

        matplotlib.rc('axes',unicode_minus = False)
Beispiel #18
0
"""Prepare the inputs to the PRESC report."""

import pandas as pd

from presc.dataset import Dataset
from presc.model import ClassificationModel

from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC

# Better quality plots
from IPython.display import set_matplotlib_formats

set_matplotlib_formats("svg")

# Load the dataset.

df = pd.read_csv("../../datasets/winequality.csv")
df = df.drop(columns=["quality"])

dataset = Dataset(df, label="recommend")
dataset.split_test_train(0.3)

# Set up the model

model = Pipeline([("scaler", StandardScaler()), ("clf", SVC(class_weight="balanced"))])
cm = ClassificationModel(model, dataset, should_train=True)

# Config options (TODO: read from file)
config = {"misclass_rate": {"num_bins": 20}}
Beispiel #19
0
from IPython.display import set_matplotlib_formats
set_matplotlib_formats('png', 'pdf')

import cobra.test
from cobra.flux_analysis import calculate_phenotype_phase_plane

model = cobra.test.create_test_model("textbook")

data = calculate_phenotype_phase_plane(
    model, "EX_glc__D_e", "EX_o2_e")
data.plot_matplotlib();
Beispiel #20
0
def latexify(column_width_pt=243.91125,
             text_width_pt=505.89,
             scale=2,
             fontsize_pt=11,
             usetex=True):
    import matplotlib.pyplot as plt

    from IPython.display import set_matplotlib_formats
    set_matplotlib_formats('pdf', 'png')

    # sorted([f.name for f in mpl.matplotlib.font_manager.fontManager.ttflist])

    fig_width_pt = column_width_pt
    inches_per_pt = 1.0 / 72.27  # to convert pt to inches
    golden_mean = 0.61803398875  # (math.sqrt(5) - 1.0) / 2.0  # Aesthetic ratio
    fig_proportion = golden_mean
    fig_width = fig_width_pt * inches_per_pt  # width in inches
    fig_height = fig_width * fig_proportion  # height in inches
    fig_size = [scale * fig_width, scale * fig_height]

    # Legend
    plt.rcParams['legend.fontsize'] = 14  # in pts (e.g. "x-small")

    # Lines
    plt.rcParams['lines.markersize'] = 8
    plt.rcParams['lines.linewidth'] = 2.0

    # Ticks
    # plt.rcParams['xtick.labelsize'] = 'x-small'
    # plt.rcParams['ytick.labelsize'] = 'x-small'
    # plt.rcParams['xtick.major.pad'] = 1
    # plt.rcParams['ytick.major.pad'] = 1

    # Axes
    plt.rcParams['axes.titlesize'] = 20
    plt.rcParams['axes.labelsize'] = 18
    # plt.rcParams['axes.labelpad'] = 0

    # LaTeX
    plt.rcParams['text.usetex'] = usetex
    plt.rcParams['text.latex.unicode'] = True
    plt.rcParams['text.latex.preview'] = False

    # use utf8 fonts becasue your computer can handle it :)
    # plots will be generated using this preamble
    plt.rcParams['text.latex.preamble'] = [
        r'\usepackage[utf8x]{inputenc}', r'\usepackage[T1]{fontenc}',
        r'\usepackage{amssymb}', r'\usepackage{amsmath}',
        r'\usepackage{wasysym}', r'\usepackage{stmaryrd}',
        r'\usepackage{subdepth}', r'\usepackage{type1cm}'
    ]

    # Fonts
    plt.rcParams['font.size'] = fontsize_pt  # font size in pts (good size 16)
    plt.rcParams[
        'font.family'] = 'sans-serif'  # , 'Merriweather Sans'  # ['DejaVu Sans Display', "serif"]
    plt.rcParams['font.serif'] = [
        'Merriweather', 'cm'
    ]  # blank entries should cause plots to inherit fonts from the document
    plt.rcParams['font.sans-serif'] = 'Merriweather Sans'
    plt.rcParams['font.monospace'] = 'Operator Mono'

    # Figure
    plt.rcParams['savefig.dpi'] = 300
    plt.rcParams['savefig.dpi'] = 75
    plt.rcParams['savefig.pad_inches'] = 0.01
    plt.rcParams['savefig.bbox'] = 'tight'
    plt.rcParams['figure.autolayout'] = False
    plt.rcParams['figure.figsize'] = fig_size
    plt.rcParams['image.interpolation'] = 'none'
    plt.rcParams['pdf.fonttype'] = 42
    plt.rcParams['ps.fonttype'] = 42
Beispiel #21
0
def use_svg_display():
    """[summary]
    use svg format to display plot in juypter
    """
    display.set_matplotlib_formats('svg')
Beispiel #22
0
            matplotlib.use('nbAgg')
        except:
            pass
            # ip.enable
            # default to inline in kernel environments
            # if hasattr(ip, 'kernel'):
            #     print('enabling inline matplotlib')
            #     ip.enable_matplotlib('inline')
            # else:
            #     print('enabling matplotlib')
            #     ip.enable_matplotlib()

    # Set format for inline plots
    from IPython.display import set_matplotlib_formats
    # %config InlineBackend.figure_formats = ['png']
    set_matplotlib_formats('png', 'svg', 'pdf', 'jpeg', quality=90)

# Load pyoti plugins
from .plugins import plugin_loader

plugin_loader.load_modules()

from . import experiment as ep
from . import evaluate as ev


def info():
    print("PyOTI - the investigator package of the PyOTIC software")
    print("Version: %s" % version())
    print()
    nb_path = os.path.abspath(".")
Beispiel #23
0
def use_svg_display():  # @save
    """使用svg格式在Jupyter中显示绘图。"""
    display.set_matplotlib_formats('svg')
Beispiel #24
0
def set_figsize(figsize=(3.5, 2.5)):
    set_matplotlib_formats('retina')  # 打印高清图。
    plt.rcParams['figure.figsize'] = figsize  # 设置图的尺寸。
Beispiel #25
0
from ipywidgets import (
    interact,
    interactive,
    IntSlider,
    widget,
    FloatText,
    FloatSlider,
    fixed,
)

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

from ..base import wiggle

set_matplotlib_formats("png")
matplotlib.rcParams["savefig.dpi"] = 70  # Change this to adjust figure size


def ViewWiggle(syndat, obsdat):
    syndata = np.load(syndat)
    obsdata = np.load(obsdat)
    dx = 20
    _, ax = plt.subplots(1, 2, figsize=(14, 8))
    kwargs = {
        "skipt": 1,
        "scale": 0.05,
        "lwidth": 1.0,
        "dx": dx,
        "sampr": 0.004,
        "clip": dx * 10.0,
Beispiel #26
0
# -*- coding: utf-8 -*-
import csv
import locale
import time
import matplotlib as mpl
import matplotlib.pyplot as plt
from cycler import cycler
from collections import defaultdict
import numpy as np
import math

locale.setlocale(locale.LC_ALL, 'en_US.UTF8')
from IPython.display import set_matplotlib_formats
set_matplotlib_formats('pdf')

onecolsize = (4, 1.5)  # Tweak based on figure's appearance in the paper
seaborn_colorblind = cycler(
    'color',
    ['#0072B2', '#D55E00', '#009E73', '#CC79A7', '#F0E442', '#56B4E9'])
seaborn_muted = cycler(
    'color',
    ['#4878CF', '#6ACC65', '#D65F5F', '#B47CC7', '#C4AD66', '#77BEDB'])


def setrcparams():
    # setup matplotlib rcparams
    plt.style.use(['seaborn-paper', 'seaborn-colorblind'])
    # color cyclers
    seaborn_colorblind = cycler(
        'color',
        ['#0072B2', '#D55E00', '#009E73', '#CC79A7', '#F0E442', '#56B4E9'])
def use_svg_display():  #@save
    """Use the svg format to display a plot in Jupyter."""
    display.set_matplotlib_formats('svg')
Beispiel #28
0
def use_svg_display():
    """Use svg format to display plot in jupyter"""
    display.set_matplotlib_formats('svg')
                accuracy += torch.mean(equals.type(torch.FloatTensor))

        model.train()

        train_losses.append(running_loss / len(trainloader))
        test_losses.append(test_loss / len(testloader))

        print("Epoch: {}/{}.. ".format(e + 1, epochs),
              "Training Loss: {:.3f}.. ".format(train_losses[-1]),
              "Test Loss: {:.3f}.. ".format(test_losses[-1]),
              "Test Accuracy: {:.3f}".format(accuracy / len(testloader)))

from IPython import get_ipython
get_ipython().run_line_magic('matplotlib', 'inline')
from IPython.display import set_matplotlib_formats
set_matplotlib_formats('retina')

import matplotlib.pyplot as plt

plt.plot(train_losses, label='Training loss')
plt.plot(test_losses, label='Validation loss')
plt.legend(frameon=False)

import helper

# Test out your network!

model.eval()

dataiter = iter(testloader)
images, labels = dataiter.next()

from __future__ import division
import os, sys, time, pickle
import itertools

get_ipython().run_line_magic('matplotlib', 'inline')
from pycocotools.coco import COCO
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.rcParams['figure.figsize'] = (8.0, 10.0)

import cv2
from IPython.display import set_matplotlib_formats
set_matplotlib_formats('jpg')
from PIL import Image, ImageDraw

import torch
import torch.nn as nn

from math import ceil, floor 


# ### Load Data

# In[17]:


dataType = 'train2014'
dataDir='' 
Beispiel #31
0
def set_fig_display_format(pic_format="svg"):
    """set figure format, such as svg(default), jpg, png, retina, pdf"""
    display.set_matplotlib_formats(pic_format)
Beispiel #32
0
def set_figsize(figsize=(3.5, 2.5)):
    set_matplotlib_formats('retina')
    plt.reParams['figure.figsize'] = figsize
Beispiel #33
0
def med_res():
    # Try vector graphic first
    from IPython.display import set_matplotlib_formats
    import matplotlib as mpl
    set_matplotlib_formats( 'png')
    mpl.rcParams['savefig.dpi'] = 144
Beispiel #34
0
def setup_matplotlib(
        output=('pdf', 'svg'), rcparams=None, usetex=True, print_errors=False):
    """ import and setup matplotlib in the jupyter notebook

    Parameters
    ----------
    output: tuple[str]
        the output formats to save to the notebook
    rcparams: None or dict
        update default parameters set for matplotlib
    usetex: bool
        if True, and the 'latex' command is available,
        create figures with LaTeX
    print_errors: bool
        print errors for unavailable rcparams

    """
    from IPython import get_ipython
    from IPython.display import set_matplotlib_formats
    import matplotlib as mpl

    try:
        from shutil import which
    except ImportError:
        from shutilwhich import which

    ipython = get_ipython()
    latex_available = which('latex') is not None
    # if not latex_available:
    #     output = [o for o in output if o != "pdf"]

    set_matplotlib_formats(*output)
    ipython.magic('matplotlib inline')
    if 'svg' in output:
        ipython.magic("config InlineBackend.figure_format = 'svg'")

    final_params = dict(MPL_OPTIONS)
    if rcparams is not None:
        final_params.update(rcparams)
    if usetex and latex_available:
        final_params.update({'text.usetex': True})
    else:
        final_params.update({'text.usetex': False})

    keyerrors = []
    valerrors = {}
    for key, val in final_params.items():
        try:
            mpl.rcParams[key] = val
        except KeyError:
            keyerrors.append(key)
        except ValueError:
            valerrors[key] = val

    if print_errors:
        if keyerrors:
            print('KeyErrors:')
            for key in keyerrors:
                print('- key')
        if valerrors:
            print('ValueError:')
            print(json.dumps(valerrors, indent=2))

    return mpl.pyplot
Beispiel #35
0
from IPython.display import set_matplotlib_formats
import numpy as np
import matplotlib.pyplot as plt
import mglearn

set_matplotlib_formats("pdf", "png")
plt.rcParams["savefig.dpi"] = 300
plt.rcParams["image.interpolation"] = "none"
np.set_printoptions(precision=3)

np, mglearn
Beispiel #36
0
def use_svg():
    display.set_matplotlib_formats('svg')
Beispiel #37
0
import random
from time import time

from IPython.display import set_matplotlib_formats
from matplotlib import pyplot as plt
import mxnet as mx
from mxnet import autograd, gluon, image, nd
from mxnet.gluon import nn, data as gdata, loss as gloss, utils as gutils
import numpy as np

# set default figure size
set_matplotlib_formats('retina')
plt.rcParams['figure.figsize'] = (3.5, 2.5)

class DataLoader(object):
    """similiar to gluon.data.DataLoader, but might be faster.

    The main difference this data loader tries to read more exmaples each
    time. But the limits are 1) all examples in dataset have the same shape, 2)
    data transfomer needs to process multiple examples at each time
    """
    def __init__(self, dataset, batch_size, shuffle, transform=None):
        self.dataset = dataset
        self.batch_size = batch_size
        self.shuffle = shuffle
        self.transform = transform

    def __iter__(self):
        data = self.dataset[:]
        X = data[0]
        y = nd.array(data[1])
Beispiel #38
0
def use_svg_display():
    # ⽤⽮量图显⽰。
    display.set_matplotlib_formats('svg')
def use_svg_display():
    # 用矢量图显示
    display.set_matplotlib_formats('svg')
Beispiel #40
0
# IPYTHON
# =======
try:
    from IPython import get_ipython
    from IPython.display import Image, Latex
    from IPython.display import set_matplotlib_formats

    _ipy_present = True
except ImportError:
    _ipy_present = False
if _ipy_present:
    ipython = get_ipython()
    if ipython is not None:
        ipython.magic("config InlineBackend.figure_format = 'svg'")
        ipython.magic("matplotlib inline")
        set_matplotlib_formats("pdf", "svg")

# NUMPY
# =====
try:
    import numpy as np
except ImportError:
    pass

# MATPLOTLIB
# ===========
try:
    import matplotlib as mpl

    _mpl_present = True
except ImportError:
Beispiel #41
0
from IPython.display import HTML
from IPython.display import set_matplotlib_formats
import matplotlib
set_matplotlib_formats('png')
matplotlib.rcParams['savefig.dpi'] = 100 # Change this to adjust figure size
from IPython.html.widgets import *

import sys
sys.path.append('./FEM3loop')
from FEM3loop import fem3loop, interactfem3loop

Beispiel #42
0
import numpy as np
import plotly.graph_objects as go
from chart_studio.plotly import plot, iplot

import matplotlib
import matplotlib.pyplot as plt  # 파이플롯 사용
from IPython.display import set_matplotlib_formats
import seaborn as sns
sns.set_style('whitegrid')

set_matplotlib_formats('retina')  # 한글코드를 더 선명하게 해주는 조치, 레티나 설정
matplotlib.rc('font', family='AppleGothic')  # 폰트 설정
matplotlib.rc('axes', unicode_minus=False)  #

import chart_studio
chart_studio.tools.set_credentials_file(username="******",
                                        api_key="32K3mAOdfE2DboHNbGmK")

# def draw_map(list_dic_geo ,list_centroid, user_district, size, dic_result_gather):
#     # # 구 코드 정리
#     # gu_code_dict = {}
#     # for num in range(25):
#     #     gu_code_dict[geo_json['features'][num]['properties']['name']] = num
#     #
#     # gu_code = gu_code_dict[gu_name]
#     # # 경도 (좌 - 우)
#     # left_lon = sorted(np.array(geo_json['features'][gu_code]['geometry']['coordinates'][0])[:, 0].tolist())[
#     #     0]  # 가장 작은 경도값 - 제일 왼쪽
#     # right_lon = sorted(np.array(geo_json['features'][gu_code]['geometry']['coordinates'][0])[:, 0].tolist())[
#     #     -1]  # 가장 큰 경도값 - 제일 오른쪽
#     # gap_lon = ((right_lon - left_lon) / size)