예제 #1
0
def _matplotlib_can_use_tex():
    """This function returns True if matplotlib can deal with LaTeX, False otherwise.
    The returned value is cached.
    """
    try:
        from matplotlib import checkdep_usetex
        return checkdep_usetex(True)
    except ImportError:
        print("This function is not available, you may be missing matplotlib.")
예제 #2
0
파일: __init__.py 프로젝트: Daoi/MLIris
def skip_if_without_tex():
    ''' Skip the test if the system does not have TeX. '''
    __tracebackhide__ = True  # pylint: disable=unused-variable
    with warnings.catch_warnings():
        warnings.filterwarnings('error')
        try:
            if matplotlib.checkdep_usetex(True):
                return
        except UserWarning as e:
            if 'Agg' in str(e):
                # Filter the warning about using Tex with Agg backend.
                return
    raise unittest.SkipTest('Skip because Tex is not in this system.')
예제 #3
0
def latexify(figsize_inches=None, font_size=12):
    """Set up matplotlib's RC params for LaTeX plotting.

    This function only needs to be called once per Python session.

    Arguments
    ---------
    figsize_inches: tuple float (optional)
        width, height of figure on inches

    font_size: int
        Size of font.
    """

    usetex = matplotlib.checkdep_usetex(True)
    if not usetex:
        raise RuntimeError(
            "Matplotlib could not find a LaTeX installation on your machine.")

    # code adapted from http://www.scipy.org/Cookbook/Matplotlib/LaTeX_Examples
    fig_width, fig_height = (figsize_inches if figsize_inches is not None else
                             (None, None))
    if fig_width is None:
        fig_width = 3.39

    if fig_height is None:
        golden_mean = (np.sqrt(5) - 1.0) / 2.0  # aesthetic ratio
        fig_height = fig_width * golden_mean  # height in inches

    max_height_inches = 8.0
    if fig_height > max_height_inches:
        print("warning: fig_height too large:" + fig_height +
              "so will reduce to" + max_height_inches + "inches.")
        fig_height = max_height_inches

    params = {
        "backend": "ps",
        "text.latex.preamble": "\\usepackage{gensymb}",
        "axes.labelsize": font_size,
        "axes.titlesize": font_size,
        "font.size": font_size,
        "legend.fontsize": font_size,
        "xtick.labelsize": font_size,
        "ytick.labelsize": font_size,
        "text.usetex": True,
        "figure.figsize": [fig_width, fig_height],
        "font.family": "serif",
    }

    matplotlib.rcParams.update(params)
예제 #4
0
def test_usetex():
    canusetex = matplotlib.checkdep_usetex(True)
    if not canusetex:
        from nose import SkipTest
        raise SkipTest('Cannot run usetex_test')
    matplotlib.rcParams['text.usetex'] = True
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.text(0.1, 0.2,
            # the \LaTeX macro exercises character sizing and placement,
            # \left[ ... \right\} draw some variable-height characters,
            # \sqrt and \frac draw horizontal rules, \mathrm changes the font
            r'\LaTeX\ $\left[\int\limits_e^{2e}'
            r'\sqrt\frac{\log^3 x}{x}\,\mathrm{d}x \right\}$',
            fontsize=24)
    ax.set_xticks([])
    ax.set_yticks([])
예제 #5
0
파일: plot_utils.py 프로젝트: jolars/celer
def configure_plt(fontsize=12):
    rc('font', **{
        'family': 'sans-serif',
        'sans-serif': ['Computer Modern Roman']
    })
    usetex = matplotlib.checkdep_usetex(True)
    params = {
        'axes.labelsize': fontsize,
        'font.size': fontsize,
        'legend.fontsize': fontsize,
        'xtick.labelsize': fontsize - 2,
        'ytick.labelsize': fontsize - 2,
        'text.usetex': usetex,
        'figure.figsize': (8, 6)
    }
    plt.rcParams.update(params)

    sns.set_palette('colorblind')
    sns.set_style("ticks")
import io
import warnings

import numpy as np
from numpy.testing import assert_almost_equal
import pytest

import matplotlib
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
from matplotlib.testing.decorators import image_comparison

with warnings.catch_warnings():
    warnings.simplefilter('ignore')
    needs_usetex = pytest.mark.skipif(
        not matplotlib.checkdep_usetex(True),
        reason="This test needs a TeX installation")


@image_comparison(baseline_images=['font_styles'])
def test_font_styles():
    from matplotlib import _get_data_path
    data_path = _get_data_path()

    def find_matplotlib_font(**kw):
        prop = FontProperties(**kw)
        path = findfont(prop, directory=data_path)
        return FontProperties(fname=path)

    from matplotlib.font_manager import FontProperties, findfont
    warnings.filterwarnings(
예제 #7
0
"""
Settings used to create LaTeX plots.
"""

###########
# Imports #
###########

import matplotlib as mpl
import matplotlib.pyplot as plt


############
# Settings #
############

plt.rcParams['axes.grid'] = True
plt.rcParams['figure.autolayout'] = True
plt.rcParams['font.size'] = 14.
plt.rcParams['legend.fontsize'] = 'small'
plt.rcParams['savefig.transparent'] = True

if mpl.checkdep_usetex(True):
    plt.rcParams['font.family'] = ['serif']
    plt.rcParams['font.serif'] = ['Computer Modern']
    plt.rcParams['text.usetex'] = True
예제 #8
0
from PIL import Image, ImageOps

from matplotlib import pyplot as plt

import persistencecurves as pc  # vectorization.  Be sure to pip install import

import pydicom  #converts dicom images to PIL. Be sure to pip install import

from pydicom_PIL import show_PIL  #just to show the image

import warnings

warnings.filterwarnings("ignore")

usetex = matplotlib.checkdep_usetex(True)  #I dont have latex)

#--------------------- Functions -----------------


def calculate_diagram_gudhi(image):

    reshaped = np.reshape(image, [image.shape[0] * image.shape[1]], order='F')
    # reshapes image to a single vector

    Complex = gudhi.CubicalComplex(dimensions=image.shape,
                                   top_dimensional_cells=reshaped)
    # creates the cubical complex from the image

    Complex.persistence()
예제 #9
0
from tempfile import NamedTemporaryFile

import numpy as np
import pytest

import matplotlib as mpl
from matplotlib import pyplot as plt, checkdep_usetex, rcParams
from matplotlib.cbook import _get_data_path
from matplotlib.ft2font import FT2Font
from matplotlib.font_manager import findfont, FontProperties
from matplotlib.backends._backend_pdf_ps import get_glyphs_subset
from matplotlib.backends.backend_pdf import PdfPages
from matplotlib.patches import Rectangle
from matplotlib.testing.decorators import check_figures_equal, image_comparison

needs_usetex = pytest.mark.skipif(not checkdep_usetex(True),
                                  reason="This test needs a TeX installation")


@image_comparison(['pdf_use14corefonts.pdf'])
def test_use14corefonts():
    rcParams['pdf.use14corefonts'] = True
    rcParams['font.family'] = 'sans-serif'
    rcParams['font.size'] = 8
    rcParams['font.sans-serif'] = ['Helvetica']
    rcParams['pdf.compression'] = 0

    text = '''A three-line text positioned just above a blue line
and containing some French characters and the euro symbol:
"Merci pépé pour les 10 €"'''
import six

import numpy as np
from io import BytesIO
import os
import tempfile
import xml.parsers.expat

import pytest

import matplotlib.pyplot as plt
from matplotlib.testing.decorators import image_comparison
import matplotlib
from matplotlib import dviread

needs_usetex = pytest.mark.xfail(not matplotlib.checkdep_usetex(True),
                                 reason="This test needs a TeX installation")


def test_visibility():
    fig = plt.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)
예제 #11
0
import numpy as np
from io import BytesIO
import os
import tempfile
import xml.parsers.expat

import pytest

import matplotlib.pyplot as plt
from matplotlib.testing.decorators import image_comparison
import matplotlib
from matplotlib import dviread


needs_usetex = pytest.mark.xfail(
    not matplotlib.checkdep_usetex(True),
    reason="This test needs a TeX installation")


def test_visibility():
    fig = plt.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)
예제 #12
0
import warnings

import numpy as np
import pytest

from matplotlib import dviread, pyplot as plt, checkdep_usetex, rcParams
from matplotlib.backends.backend_pdf import PdfPages
from matplotlib.testing.compare import compare_images
from matplotlib.testing.decorators import image_comparison
from matplotlib.testing.determinism import (_determinism_source_date_epoch,
                                            _determinism_check)

with warnings.catch_warnings():
    warnings.simplefilter('ignore')
    needs_usetex = pytest.mark.skipif(
        not checkdep_usetex(True), reason="This test needs a TeX installation")


@image_comparison(baseline_images=['pdf_use14corefonts'], extensions=['pdf'])
def test_use14corefonts():
    rcParams['pdf.use14corefonts'] = True
    rcParams['font.family'] = 'sans-serif'
    rcParams['font.size'] = 8
    rcParams['font.sans-serif'] = ['Helvetica']
    rcParams['pdf.compression'] = 0

    text = '''A three-line text positioned just above a blue line
and containing some French characters and the euro symbol:
"Merci pépé pour les 10 €"'''

    fig = plt.figure()
예제 #13
0
import io
import os
import sys
import tempfile

import numpy as np
import pytest

from matplotlib import dviread, pyplot as plt, checkdep_usetex, rcParams
from matplotlib.backends.backend_pdf import PdfPages
from matplotlib.testing.compare import compare_images
from matplotlib.testing.decorators import image_comparison
from matplotlib.testing.determinism import (_determinism_source_date_epoch,
                                            _determinism_check)

needs_usetex = pytest.mark.xfail(not checkdep_usetex(True),
                                 reason="This test needs a TeX installation")


@image_comparison(baseline_images=['pdf_use14corefonts'], extensions=['pdf'])
def test_use14corefonts():
    rcParams['pdf.use14corefonts'] = True
    rcParams['font.family'] = 'sans-serif'
    rcParams['font.size'] = 8
    rcParams['font.sans-serif'] = ['Helvetica']
    rcParams['pdf.compression'] = 0

    text = u'''A three-line text positioned just above a blue line
and containing some French characters and the euro symbol:
"Merci pépé pour les 10 €"'''
def usetex():
    if not mpl.checkdep_usetex(True):
        pytest.skip('Missing TeX of Ghostscript or dvipng')
    mpl.rcParams['text.usetex'] = True
예제 #15
0
import pytest

import matplotlib
from matplotlib.testing.decorators import image_comparison
import matplotlib.pyplot as plt


@pytest.mark.skipif(not matplotlib.checkdep_usetex(True),
                    reason='Missing TeX or Ghostscript or dvipng')
@image_comparison(baseline_images=['test_usetex'],
                  extensions=['pdf', 'png'],
                  tol=0.3)
def test_usetex():
    matplotlib.rcParams['text.usetex'] = True
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.text(0.1, 0.2,
            # the \LaTeX macro exercises character sizing and placement,
            # \left[ ... \right\} draw some variable-height characters,
            # \sqrt and \frac draw horizontal rules, \mathrm changes the font
            r'\LaTeX\ $\left[\int\limits_e^{2e}'
            r'\sqrt\frac{\log^3 x}{x}\,\mathrm{d}x \right\}$',
            fontsize=24)
    ax.set_xticks([])
    ax.set_yticks([])
예제 #16
0
    legend.set_draggable(True)
    assert legend.get_draggable()
    legend.set_draggable(False)
    assert not legend.get_draggable()


def test_alpha_handles():
    x, n, hh = plt.hist([1, 2, 3], alpha=0.25, label='data', color='red')
    legend = plt.legend()
    for lh in legend.legendHandles:
        lh.set_alpha(1.0)
    assert lh.get_facecolor()[:-1] == hh[1].get_facecolor()[:-1]
    assert lh.get_edgecolor()[:-1] == hh[1].get_edgecolor()[:-1]


@pytest.mark.skipif(not mpl.checkdep_usetex(True),
                    reason="This test needs a TeX installation")
def test_usetex_no_warn(caplog):
    mpl.rcParams['font.family'] = 'serif'
    mpl.rcParams['font.serif'] = 'Computer Modern'
    mpl.rcParams['text.usetex'] = True

    fig, ax = plt.subplots()
    ax.plot(0, 0, label='input')
    ax.legend(title="My legend")

    fig.canvas.draw()
    assert "Font family ['serif'] not found." not in caplog.text


def test_warn_big_data_best_loc():
예제 #17
0
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

import pytest

import matplotlib
from matplotlib.testing.decorators import image_comparison
from matplotlib.compat.subprocess import check_output
import matplotlib.pyplot as plt


@pytest.mark.skipif(not matplotlib.checkdep_usetex(True),
                    reason='Missing TeX or Ghostscript or dvipng')
@image_comparison(baseline_images=['test_usetex'],
                  extensions=['pdf', 'png'],
                  tol=0.3)
def test_usetex():
    matplotlib.rcParams['text.usetex'] = True
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.text(
        0.1,
        0.2,
        # the \LaTeX macro exercises character sizing and placement,
        # \left[ ... \right\} draw some variable-height characters,
        # \sqrt and \frac draw horizontal rules, \mathrm changes the font
        r'\LaTeX\ $\left[\int\limits_e^{2e}'
        r'\sqrt\frac{\log^3 x}{x}\,\mathrm{d}x \right\}$',
        fontsize=24)
    ax.set_xticks([])
    ax.set_yticks([])
예제 #18
0
import numpy as np
import pytest

from matplotlib import dviread, pyplot as plt, checkdep_usetex, rcParams
from matplotlib.backends.backend_pdf import PdfPages
from matplotlib.testing.compare import compare_images
from matplotlib.testing.decorators import image_comparison
from matplotlib.testing.determinism import (_determinism_source_date_epoch,
                                            _determinism_check)


with warnings.catch_warnings():
    warnings.simplefilter('ignore')
    needs_usetex = pytest.mark.skipif(
        not checkdep_usetex(True),
        reason="This test needs a TeX installation")


@image_comparison(baseline_images=['pdf_use14corefonts'],
                  extensions=['pdf'])
def test_use14corefonts():
    rcParams['pdf.use14corefonts'] = True
    rcParams['font.family'] = 'sans-serif'
    rcParams['font.size'] = 8
    rcParams['font.sans-serif'] = ['Helvetica']
    rcParams['pdf.compression'] = 0

    text = '''A three-line text positioned just above a blue line
and containing some French characters and the euro symbol:
"Merci pépé pour les 10 €"'''
예제 #19
0
from astropy.wcs import WCS
from astropy.io import fits
from astropy.coordinates import SkyCoord

from astropy.utils.data import get_pkg_data_filename

from astropy.visualization.wcsaxes.core import WCSAxes
from astropy.visualization.wcsaxes.frame import (EllipticalFrame,
                                                 RectangularFrame,
                                                 RectangularFrame1D)
from astropy.visualization.wcsaxes.utils import get_coord_meta
from astropy.visualization.wcsaxes.transforms import CurvedTransform

ft_version = Version(matplotlib.ft2font.__freetype_version__)
FREETYPE_261 = ft_version == Version("2.6.1")
TEX_UNAVAILABLE = not matplotlib.checkdep_usetex(True)


def teardown_function(function):
    plt.close('all')


def test_grid_regression(ignore_matplotlibrc):
    # Regression test for a bug that meant that if the rc parameter
    # axes.grid was set to True, WCSAxes would crash upon initalization.
    plt.rc('axes', grid=True)
    fig = plt.figure(figsize=(3, 3))
    WCSAxes(fig, [0.1, 0.1, 0.8, 0.8])


def test_format_coord_regression(ignore_matplotlibrc, tmpdir):
예제 #20
0
import os
from pathlib import Path
import sys
from tempfile import NamedTemporaryFile

import numpy as np
import pytest

import matplotlib as mpl
from matplotlib import dviread, pyplot as plt, checkdep_usetex, rcParams
from matplotlib.backends.backend_pdf import PdfPages
from matplotlib.testing.decorators import check_figures_equal, image_comparison


needs_usetex = pytest.mark.skipif(
    not checkdep_usetex(True),
    reason="This test needs a TeX installation")


@image_comparison(['pdf_use14corefonts.pdf'])
def test_use14corefonts():
    rcParams['pdf.use14corefonts'] = True
    rcParams['font.family'] = 'sans-serif'
    rcParams['font.size'] = 8
    rcParams['font.sans-serif'] = ['Helvetica']
    rcParams['pdf.compression'] = 0

    text = '''A three-line text positioned just above a blue line
and containing some French characters and the euro symbol:
"Merci pépé pour les 10 €"'''
예제 #21
0
import warnings
import xml.parsers.expat

import pytest

import matplotlib as mpl
from matplotlib import dviread
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
from matplotlib.testing.decorators import image_comparison


with warnings.catch_warnings():
    warnings.simplefilter('ignore')
    needs_usetex = pytest.mark.skipif(
        not mpl.checkdep_usetex(True),
        reason="This test needs a TeX installation")


def test_visibility():
    fig, ax = plt.subplots()

    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)

    fd = BytesIO()
예제 #22
0
    assert legend.get_draggable()
    legend.set_draggable(False)
    assert not legend.get_draggable()


def test_alpha_handles():
    x, n, hh = plt.hist([1, 2, 3], alpha=0.25, label='data', color='red')
    legend = plt.legend()
    for lh in legend.legendHandles:
        lh.set_alpha(1.0)
    assert lh.get_facecolor()[:-1] == hh[1].get_facecolor()[:-1]
    assert lh.get_edgecolor()[:-1] == hh[1].get_edgecolor()[:-1]


@pytest.mark.skipif(
    not mpl.checkdep_usetex(True),
    reason="This test needs a TeX installation")
def test_usetex_no_warn(caplog):
    mpl.rcParams['font.family'] = 'serif'
    mpl.rcParams['font.serif'] = 'Computer Modern'
    mpl.rcParams['text.usetex'] = True

    fig, ax = plt.subplots()
    ax.plot(0, 0, label='input')
    ax.legend(title="My legend")

    fig.canvas.draw()
    assert "Font family ['serif'] not found." not in caplog.text


def test_warn_big_data_best_loc():
예제 #23
0
def is_tex_available():
    return checkdep_usetex(True)