Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 5 additions & 6 deletions lib/matplotlib/backend_bases.py
Original file line number Diff line number Diff line change
Expand Up @@ -3142,14 +3142,13 @@ def _get_image_filename(self, image):
if not image:
return None

basedir = os.path.join(rcParams['datapath'], 'images')
possible_images = (
basedir = cbook._get_data_path("images")
for fname in [
image,
image + self._icon_extension,
os.path.join(basedir, image),
os.path.join(basedir, image) + self._icon_extension)

for fname in possible_images:
str(basedir / image),
str(basedir / (image + self._icon_extension)),
]:
if os.path.isfile(fname):
return fname

Expand Down
8 changes: 3 additions & 5 deletions lib/matplotlib/backends/_backend_tk.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
import numpy as np

import matplotlib
from matplotlib import backend_tools, rcParams
from matplotlib import backend_tools, cbook, rcParams
from matplotlib.backend_bases import (
_Backend, FigureCanvasBase, FigureManagerBase, NavigationToolbar2,
StatusbarBase, TimerBase, ToolContainerBase, cursors)
Expand Down Expand Up @@ -547,8 +547,7 @@ def set_cursor(self, cursor):
window.update_idletasks()

def _Button(self, text, file, command, extension='.gif'):
img_file = os.path.join(
rcParams['datapath'], 'images', file + extension)
img_file = str(cbook._get_data_path('images', file + extension))
im = tk.PhotoImage(master=self, file=img_file)
b = tk.Button(
master=self, text=text, padx=2, pady=2, image=im, command=command)
Expand Down Expand Up @@ -884,8 +883,7 @@ def new_figure_manager_given_figure(cls, num, figure):
# Tkinter doesn't allow colour icons on linux systems, but tk>=8.5
# has a iconphoto command which we call directly. Source:
# http://mail.python.org/pipermail/tkinter-discuss/2006-November/000954.html
icon_fname = os.path.join(
rcParams['datapath'], 'images', 'matplotlib.ppm')
icon_fname = str(cbook._get_data_path('images/matplotlib.ppm'))
icon_img = tk.PhotoImage(file=icon_fname, master=window)
try:
window.iconphoto(False, icon_img)
Expand Down
8 changes: 3 additions & 5 deletions lib/matplotlib/backends/backend_gtk3.py
Original file line number Diff line number Diff line change
Expand Up @@ -494,16 +494,15 @@ def draw_rubberband(self, event, x0, y0, x1, y1):

def _init_toolbar(self):
self.set_style(Gtk.ToolbarStyle.ICONS)
basedir = os.path.join(rcParams['datapath'], 'images')

self._gtk_ids = {}
for text, tooltip_text, image_file, callback in self.toolitems:
if text is None:
self.insert(Gtk.SeparatorToolItem(), -1)
continue
fname = os.path.join(basedir, image_file + '.png')
image = Gtk.Image()
image.set_from_file(fname)
image.set_from_file(
str(cbook._get_data_path('images', image_file + '.png')))
self._gtk_ids[text] = tbutton = Gtk.ToolButton()
tbutton.set_label(text)
tbutton.set_icon_widget(image)
Expand Down Expand Up @@ -952,8 +951,7 @@ def trigger(self, *args, **kwargs):
icon_filename = 'matplotlib.png'
else:
icon_filename = 'matplotlib.svg'
window_icon = os.path.join(
matplotlib.rcParams['datapath'], 'images', icon_filename)
window_icon = str(cbook._get_data_path('images', icon_filename))


def error_msg_gtk(msg, parent=None):
Expand Down
18 changes: 6 additions & 12 deletions lib/matplotlib/backends/backend_macosx.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,14 @@
import os

import matplotlib
from matplotlib import cbook, rcParams
from matplotlib._pylab_helpers import Gcf
from matplotlib.backends import _macosx
from matplotlib.backends.backend_agg import FigureCanvasAgg
from matplotlib.backend_bases import (
_Backend, FigureCanvasBase, FigureManagerBase, NavigationToolbar2,
TimerBase)

from matplotlib.figure import Figure
from matplotlib import cbook, rcParams

from matplotlib.widgets import SubplotTool

import matplotlib
from matplotlib.backends import _macosx

from .backend_agg import FigureCanvasAgg


########################################################################
#
Expand Down Expand Up @@ -139,8 +133,8 @@ def __init__(self, canvas):
NavigationToolbar2.__init__(self, canvas)

def _init_toolbar(self):
basedir = os.path.join(rcParams['datapath'], "images")
_macosx.NavigationToolbar2.__init__(self, basedir)
_macosx.NavigationToolbar2.__init__(
self, str(cbook._get_data_path('images')))

def draw_rubberband(self, event, x0, y0, x1, y1):
self.canvas.set_rubberband(int(x0), int(y0), int(x1), int(y1))
Expand Down
9 changes: 4 additions & 5 deletions lib/matplotlib/backends/backend_pdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -440,8 +440,6 @@ def __init__(self, filename, metadata=None):
fh = filename
self.passed_in_file_object = True

self._core14fontdir = os.path.join(
rcParams['datapath'], 'fonts', 'pdfcorefonts')
self.fh = fh
self.currentstream = None # stream object to write to, if any
fh.write(b"%PDF-1.4\n") # 1.4 is the first version to have alpha
Expand Down Expand Up @@ -635,10 +633,11 @@ def fontName(self, fontprop):
filename = fontprop
elif rcParams['pdf.use14corefonts']:
filename = findfont(
fontprop, fontext='afm', directory=self._core14fontdir)
fontprop, fontext='afm', directory=RendererPdf._afm_font_dir)
if filename is None:
filename = findfont(
"Helvetica", fontext='afm', directory=self._core14fontdir)
"Helvetica",
fontext='afm', directory=RendererPdf._afm_font_dir)
else:
filename = findfont(fontprop)

Expand Down Expand Up @@ -1571,7 +1570,7 @@ class RendererPdf(_backend_pdf_ps.RendererPDFPSBase):
def afm_font_cache(self, _cache=cbook.maxdict(50)):
return _cache

_afm_font_dir = pathlib.Path(rcParams["datapath"], "fonts", "pdfcorefonts")
_afm_font_dir = cbook._get_data_path("fonts/pdfcorefonts")
_use_afm_rc_name = "pdf.use14corefonts"

def __init__(self, file, image_dpi, height, width):
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/backends/backend_ps.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ class RendererPS(_backend_pdf_ps.RendererPDFPSBase):
def afmfontd(self, _cache=cbook.maxdict(50)):
return _cache

_afm_font_dir = pathlib.Path(rcParams["datapath"], "fonts", "afm")
_afm_font_dir = cbook._get_data_path("fonts/afm")
_use_afm_rc_name = "ps.useafm"

def __init__(self, width, height, pswriter, imagedpi=72):
Expand Down
8 changes: 3 additions & 5 deletions lib/matplotlib/backends/backend_qt5.py
Original file line number Diff line number Diff line change
Expand Up @@ -535,8 +535,7 @@ def __init__(self, canvas, num):
self.window.closing.connect(self._widgetclosed)

self.window.setWindowTitle("Figure %d" % num)
image = os.path.join(matplotlib.rcParams['datapath'],
'images', 'matplotlib.svg')
image = str(cbook._get_data_path('images/matplotlib.svg'))
self.window.setWindowIcon(QtGui.QIcon(image))

# Give the keyboard focus to the figure instead of the
Expand Down Expand Up @@ -676,7 +675,7 @@ def _icon(self, name):
return QtGui.QIcon(pm)

def _init_toolbar(self):
self.basedir = os.path.join(matplotlib.rcParams['datapath'], 'images')
self.basedir = str(cbook._get_data_path('images'))

for text, tooltip_text, image_file, callback in self.toolitems:
if text is None:
Expand Down Expand Up @@ -792,8 +791,7 @@ def remove_rubberband(self):
self.canvas.drawRectangle(None)

def configure_subplots(self):
image = os.path.join(matplotlib.rcParams['datapath'],
'images', 'matplotlib.png')
image = str(cbook._get_data_path('images/matplotlib.png'))
dia = SubplotToolQt(self.canvas.figure, self.canvas.parent())
dia.setWindowIcon(QtGui.QIcon(image))
dia.exec_()
Expand Down
6 changes: 3 additions & 3 deletions lib/matplotlib/backends/backend_webagg.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
import tornado.ioloop
import tornado.websocket

from matplotlib import rcParams
from matplotlib import cbook, rcParams
from matplotlib.backend_bases import _Backend
from matplotlib._pylab_helpers import Gcf
from . import backend_webagg_core as core
Expand Down Expand Up @@ -65,8 +65,8 @@ class WebAggApplication(tornado.web.Application):
class FavIcon(tornado.web.RequestHandler):
def get(self):
self.set_header('Content-Type', 'image/png')
image_path = Path(rcParams["datapath"], "images", "matplotlib.png")
self.write(image_path.read_bytes())
self.write(
cbook._get_data_path('images/matplotlib.png').read_bytes())

class SingleFigurePage(tornado.web.RequestHandler):
def __init__(self, application, request, *, url_prefix='', **kwargs):
Expand Down
22 changes: 8 additions & 14 deletions lib/matplotlib/backends/backend_wx.py
Original file line number Diff line number Diff line change
Expand Up @@ -1226,27 +1226,21 @@ def _load_bitmap(filename):
matplotlib library is installed. The filename parameter should not
contain any path information as this is determined automatically.

Returns a wx.Bitmap object
Returns a wx.Bitmap object.
"""

basedir = os.path.join(rcParams['datapath'], 'images')

bmpFilename = os.path.normpath(os.path.join(basedir, filename))
if not os.path.exists(bmpFilename):
raise IOError('Could not find bitmap file "%s"; dying' % bmpFilename)

bmp = wx.Bitmap(bmpFilename)
return bmp
path = cbook._get_data_path('images', filename)
if not path.exists():
raise IOError(f"Could not find bitmap file '{path}'; dying")
return wx.Bitmap(str(path))


def _set_frame_icon(frame):
# set frame icon
bundle = wx.IconBundle()
for image in ('matplotlib.png', 'matplotlib_large.png'):
image = os.path.join(matplotlib.rcParams['datapath'], 'images', image)
if not os.path.exists(image):
try:
icon = wx.Icon(_load_bitmap(image))
except IOError:
continue
icon = wx.Icon(_load_bitmap(image))
if not icon.IsOk():
return
bundle.AddIcon(icon)
Expand Down
16 changes: 6 additions & 10 deletions lib/matplotlib/backends/qt_editor/figureoptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,14 @@

"""Module that provides a GUI-based editor for matplotlib's figure options."""

import os.path
import re

import matplotlib
from matplotlib import cm, colors as mcolors, markers, image as mimage
from matplotlib import cbook, cm, colors as mcolors, markers, image as mimage
from matplotlib.backends.qt_compat import QtGui
from matplotlib.backends.qt_editor import _formlayout


def get_icon(name):
basedir = os.path.join(matplotlib.rcParams['datapath'], 'images')
return QtGui.QIcon(os.path.join(basedir, name))


LINESTYLES = {'-': 'Solid',
'--': 'Dashed',
'-.': 'DashDot',
Expand Down Expand Up @@ -257,8 +251,10 @@ def apply_callback(data):
if not (axes.get_xlim() == orig_xlim and axes.get_ylim() == orig_ylim):
figure.canvas.toolbar.push_current()

data = _formlayout.fedit(datalist, title="Figure options", parent=parent,
icon=get_icon('qt4_editor_options.svg'),
apply=apply_callback)
data = _formlayout.fedit(
datalist, title="Figure options", parent=parent,
icon=QtGui.QIcon(
str(cbook._get_data_path('images', 'qt4_editor_options.svg'))),
apply=apply_callback)
if data is not None:
apply_callback(data)
9 changes: 9 additions & 0 deletions lib/matplotlib/cbook/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -436,6 +436,15 @@ def get_sample_data(fname, asfileobj=True):
return str(path)


def _get_data_path(*args):
"""
Return the `Path` to a resource file provided by Matplotlib.

``*args`` specify a path relative to the base data path.
"""
return Path(matplotlib.get_data_path(), *args)


def flatten(seq, scalarp=is_scalar_or_string):
"""
Return a generator of flattened nested containers
Expand Down
6 changes: 2 additions & 4 deletions lib/matplotlib/font_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -946,10 +946,8 @@ def __init__(self, size=None, weight='normal'):
self.__default_weight = weight
self.default_size = size

paths = [os.path.join(rcParams['datapath'], 'fonts', 'ttf'),
os.path.join(rcParams['datapath'], 'fonts', 'afm'),
os.path.join(rcParams['datapath'], 'fonts', 'pdfcorefonts')]

paths = [cbook._get_data_path('fonts', subdir)
for subdir in ['ttf', 'afm', 'pdfcorefonts']]
# Create list of font paths
for pathname in ['TTFPATH', 'AFMPATH']:
if pathname in os.environ:
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/mathtext.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@

ParserElement.enablePackrat()

from matplotlib import cbook, colors as mcolors, get_data_path, rcParams
from matplotlib import cbook, colors as mcolors, rcParams
from matplotlib.afm import AFM
from matplotlib.cbook import get_realpath_and_stat
from matplotlib.ft2font import FT2Image, KERNING_DEFAULT, LOAD_NO_HINTING
Expand Down Expand Up @@ -1078,7 +1078,7 @@ class StandardPsFonts(Fonts):
Unlike the other font classes, BakomaFont and UnicodeFont, this
one requires the Ps backend.
"""
basepath = os.path.join(get_data_path(), 'fonts', 'afm')
basepath = str(cbook._get_data_path('fonts/afm'))

fontmap = { 'cal' : 'pzcmi8a', # Zapf Chancery
'rm' : 'pncr8a', # New Century Schoolbook
Expand Down
10 changes: 4 additions & 6 deletions lib/matplotlib/tests/test_rcparams.py
Original file line number Diff line number Diff line change
Expand Up @@ -433,9 +433,8 @@ def test_rcparams_reset_after_fail():
def test_if_rctemplate_is_up_to_date():
# This tests if the matplotlibrc.template file contains all valid rcParams.
deprecated = {*mpl._all_deprecated, *mpl._deprecated_remain_as_none}
path_to_rc = os.path.join(mpl.get_data_path(), 'matplotlibrc')
with open(path_to_rc, "r") as f:
rclines = f.readlines()
with cbook._get_data_path('matplotlibrc').open() as file:
rclines = file.readlines()
missing = {}
for k, v in mpl.defaultParams.items():
if k[0] == "_":
Expand All @@ -457,9 +456,8 @@ def test_if_rctemplate_is_up_to_date():
def test_if_rctemplate_would_be_valid(tmpdir):
# This tests if the matplotlibrc.template file would result in a valid
# rc file if all lines are uncommented.
path_to_rc = os.path.join(mpl.get_data_path(), 'matplotlibrc')
with open(path_to_rc, "r") as f:
rclines = f.readlines()
with cbook._get_data_path('matplotlibrc').open() as file:
rclines = file.readlines()
newlines = []
for line in rclines:
if line[0] == "#":
Expand Down
4 changes: 1 addition & 3 deletions lib/matplotlib/tests/test_text.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,10 @@

@image_comparison(['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)
path = findfont(prop, directory=matplotlib.get_data_path())
return FontProperties(fname=path)

from matplotlib.font_manager import FontProperties, findfont
Expand Down