Меню Рубрики

Python matplotlib установка windows

Installation Guide¶

If you wish to contribute to the project, it’s recommended you install the latest development version .

Installing an official release¶

Matplotlib and its dependencies are available as wheel packages for macOS, Windows and Linux distributions:

If this command results in Matplotlib being compiled from source and there’s trouble with the compilation, you can add —prefer-binary to select the newest version of Matplotlib for which there is a precompiled wheel for your OS and Python.

The following backends work out of the box: Agg, ps, pdf, svg

Python is typically shipped with tk bindings which are used by TkAgg.

For support of other GUI frameworks, LaTeX rendering, saving animations and a larger selection of file formats, you need to install additional dependencies .

Although not required, we suggest also installing IPython for interactive use. To easily install a complete Scientific Python stack, see Scientific Python Distributions below.

Test data¶

The wheels ( *.whl ) on the PyPI download page do not contain test data or example code.

If you want to try the many demos that come in the Matplotlib source distribution, download the *.tar.gz file and look in the examples subdirectory.

To run the test suite:

  • extract the lib/matplotlib/tests or lib/mpl_toolkits/tests directories from the source distribution.
  • install test dependencies: pytest, MiKTeX, GhostScript, ffmpeg, avconv, ImageMagick, and Inkscape.
  • run python -mpytest .

Third-party distributions of Matplotlib¶

Scientific Python Distributions¶

Anaconda and ActiveState are excellent choices that «just work» out of the box for Windows, macOS and common Linux platforms. WinPython is an option for Windows users. All of these distributions include Matplotlib and lots of other useful (data) science tools.

Linux: using your package manager¶

If you are on Linux, you might prefer to use your package manager. Matplotlib is packaged for almost every major Linux distribution.

  • Debian / Ubuntu: sudo apt-get install python3-matplotlib
  • Fedora: sudo dnf install python3-matplotlib
  • Red Hat: sudo yum install python3-matplotlib
  • Arch: sudo pacman -S python-matplotlib

Installing from source¶

If you are interested in contributing to Matplotlib development, running the latest source code, or just like to build everything yourself, it is not difficult to build Matplotlib from source. Grab the latest tar.gz release file from the PyPI files page, or if you want to develop Matplotlib or just need the latest bugfixed version, grab the latest git version, and see Install from source .

Matplotlib can be installed from the source directory with a simple

We provide a setup.cfg file which you can use to customize the build process. For example, which default backend to use, whether some of the optional libraries that Matplotlib ships with are installed, and so on. This file will be particularly useful to those packaging Matplotlib.

Dependencies¶

Matplotlib requires the following dependencies:

Optionally, you can also install a number of packages to enable better user interface toolkits. See What is a backend? for more details on the optional Matplotlib backends and the capabilities they provide.

  • Tk (>= 8.3, != 8.6.0 or 8.6.1): for the Tk-based backends.
  • PyQt4 (>= 4.6) or PySide (>= 1.0.3) [1]: for the Qt4-based backends.
  • PyQt5 or PySide2: for the Qt5-based backends.
  • PyGObject: for the GTK3-based backends [2].
  • wxPython (>= 4) [3]: for the wx-based backends.
  • pycairo (>= 1.11.0) or cairocffi (>= 0.8): for the GTK3 and/or cairo-based backends.
  • Tornado: for the WebAgg backend.
[1] PySide cannot be pip-installed on Linux (but can be conda-installed).
[2] If using pip (and not conda), PyGObject must be built from source; see https://pygobject.readthedocs.io/en/latest/devguide/dev_environ.html.
[3] If using pip (and not conda) on Linux, wxPython wheels must be manually downloaded from https://wxpython.org/pages/downloads/.

For better support of animation output format and image file formats, LaTeX, etc., you can install the following:

  • ffmpeg: for saving movies.
  • ImageMagick: for saving animated gifs.
  • LaTeX (with cm-super ) and GhostScript (>=9.0) : for rendering text with LaTeX.
  • fontconfig (>= 2.7): for detection of system fonts on Linux.

FreeType and Qhull¶

Matplotlib depends on FreeType (>= 2.3), a font rendering library, and on Qhull (>= 2015.2), a library for computing triangulations. By default (except on AIX) Matplotlib downloads and builds its own copy of FreeType (this is necessary to run the test suite, because different versions of FreeType rasterize characters differently), and uses its own copy of Qhull.

To force Matplotlib to use a copy of FreeType or Qhull already installed in your system, create a setup.cfg file with the following contents:

before running python -m pip install . .

In this case, you need to install the FreeType and Qhull library and headers. This can be achieved using a package manager, e.g. for FreeType:

(adapt accordingly for Qhull).

On Linux and macOS, it is also recommended to install pkg-config, a helper tool for locating FreeType:

If not using pkg-config (in particular on Windows), you may need to set the include path (to the library headers) and link path (to the libraries) explicitly, if they are not in standard locations. This can be done using standard environment variables — on Linux and OSX:

Matplotlib always uses its own copies of the following libraries:

  • Agg : the Anti-Grain Geometry C++ rendering engine;
  • ttconv : a TrueType font utility.

Building on Windows¶

Compiling Matplotlib (or any other extension module, for that matter) requires Visual Studio 2015 or later.

If you are building your own Matplotlib wheels (or sdists), note that any DLLs that you copy into the source tree will be packaged too.

Источник

Installing¶

If you wish to contribute to the project, it’s recommended you install the latest development version .

Installing an official release¶

Matplotlib and its dependencies are available as wheel packages for macOS, Windows and Linux distributions:

The following backends work out of the box: Agg, ps, pdf, svg and TkAgg.

For support of other GUI frameworks, LaTeX rendering, saving animations and a larger selection of file formats, you may need to install additional dependencies .

Although not required, we suggest also installing IPython for interactive use. To easily install a complete Scientific Python stack, see Scientific Python Distributions below.

Test data¶

The wheels ( *.whl ) on the PyPI download page do not contain test data or example code.

If you want to try the many demos that come in the Matplotlib source distribution, download the *.tar.gz file and look in the examples subdirectory.

To run the test suite:

  • extract the lib/matplotlib/tests or lib/mpl_toolkits/tests directories from the source distribution;
  • install test dependencies: pytest, Pillow, MiKTeX, GhostScript, ffmpeg, avconv, ImageMagick, and Inkscape;
  • run python -mpytest .

Third-party distributions of Matplotlib¶

Scientific Python Distributions¶

Anaconda and Canopy and ActiveState are excellent choices that «just work» out of the box for Windows, macOS and common Linux platforms. WinPython is an option for Windows users. All of these distributions include Matplotlib and lots of other useful (data) science tools.

Linux: using your package manager¶

If you are on Linux, you might prefer to use your package manager. Matplotlib is packaged for almost every major Linux distribution.

  • Debian / Ubuntu: sudo apt-get install python3-matplotlib
  • Fedora: sudo dnf install python3-matplotlib
  • Red Hat: sudo yum install python3-matplotlib
  • Arch: sudo pacman -S python-matplotlib

Installing from source¶

If you are interested in contributing to Matplotlib development, running the latest source code, or just like to build everything yourself, it is not difficult to build Matplotlib from source. Grab the latest tar.gz release file from the PyPI files page, or if you want to develop Matplotlib or just need the latest bugfixed version, grab the latest git version, and see Install from source .

The standard environment variables CC , CXX , PKG_CONFIG are respected. This means you can set them if your toolchain is prefixed. This may be used for cross compiling.

Once you have satisfied the requirements detailed below (mainly Python, NumPy, libpng and FreeType), you can build Matplotlib.

We provide a setup.cfg file which you can use to customize the build process. For example, which default backend to use, whether some of the optional libraries that Matplotlib ships with are installed, and so on. This file will be particularly useful to those packaging Matplotlib.

If you have installed prerequisites to nonstandard places and need to inform Matplotlib where they are, edit setupext.py and add the base dirs to the basedir dictionary entry for your sys.platform ; e.g., if the header of some required library is in /some/path/include/someheader.h , put /some/path in the basedir list for your platform.

Dependencies¶

Matplotlib requires the following dependencies:

Optionally, you can also install a number of packages to enable better user interface toolkits. See What is a backend? for more details on the optional Matplotlib backends and the capabilities they provide.

  • tk (>= 8.3, != 8.6.0 or 8.6.1): for the Tk-based backends;
  • PyQt4 (>= 4.6) or PySide (>= 1.0.3): for the Qt4-based backends;
  • PyQt5: for the Qt5-based backends;
  • PyGObject: for the GTK3-based backends;
  • wxpython (>= 4): for the WX-based backends;
  • cairocffi (>= 0.8) or pycairo: for the cairo-based backends;
  • Tornado: for the WebAgg backend;

For better support of animation output format and image file formats, LaTeX, etc., you can install the following:

  • ffmpeg/avconv: for saving movies;
  • ImageMagick: for saving animated gifs;
  • Pillow (>= 3.4): for a larger selection of image file formats: JPEG, BMP, and TIFF image files;
  • LaTeX and GhostScript (>=9.0) : for rendering text with LaTeX.

Matplotlib depends on non-Python libraries.

On Linux and OSX, pkg-config can be used to find required non-Python libraries and thus make the install go more smoothly if the libraries and headers are not in the expected locations.

If not using pkg-config (in particular on Windows), you may need to set the include path (to the FreeType, libpng, and zlib headers) and link path (to the FreeType, libpng, and zlib libraries) explicitly, if they are not in standard locations. This can be done using standard environment variables — on Linux and OSX:

where . means «also give, in the same format, the directories containing png.h and zlib.h for the include path, and for libpng.so / png.lib and libz.so / z.lib for the link path.»

The following libraries are shipped with Matplotlib:

  • Agg : the Anti-Grain Geometry C++ rendering engine;
  • qhull : to compute Delaunay triangulation;
  • ttconv : a TrueType font utility.

Building on Linux¶

It is easiest to use your system package manager to install the dependencies.

If you are on Debian/Ubuntu, you can get all the dependencies required to build Matplotlib with:

If you are on Fedora, you can get all the dependencies required to build Matplotlib with:

If you are on RedHat, you can get all the dependencies required to build Matplotlib by first installing yum-builddep and then running:

These commands do not build Matplotlib, but instead get and install the build dependencies, which will make building from source easier.

Building on macOS¶

The build situation on macOS is complicated by the various places one can get the libpng and FreeType requirements (MacPorts, Fink, /usr/X11R6), the different architectures (e.g., x86, ppc, universal), and the different macOS versions (e.g., 10.4 and 10.5). We recommend that you build the way we do for the macOS release: get the source from the tarball or the git repository and install the required dependencies through a third-party package manager. Two widely used package managers are Homebrew, and MacPorts. The following example illustrates how to install libpng and FreeType using brew :

If you are using MacPorts, execute the following instead:

After installing the above requirements, install Matplotlib from source by executing:

Note that your environment is somewhat important. Some conda users have found that, to run the tests, their PYTHONPATH must include /path/to/anaconda/. /site-packages and their DYLD_FALLBACK_LIBRARY_PATH must include /path/to/anaconda/lib.

Building on Windows¶

The Python shipped from https://www.python.org is compiled with Visual Studio 2015 for 3.5+. Python extensions should be compiled with the same compiler, see e.g. https://packaging.python.org/guides/packaging-binary-extensions/#setting-up-a-build-environment-on-windows for how to set up a build environment.

Since there is no canonical Windows package manager, the methods for building FreeType, zlib, and libpng from source code are documented as a build script at matplotlib-winbuild.

There are a few possibilities to build Matplotlib on Windows:

  • Wheels via matplotlib-winbuild
  • Wheels by using conda packages (see below)
  • Conda packages (see below)

Wheel builds using conda packages¶

This is a wheel build, but we use conda packages to get all the requirements. The binary requirements (png, FreeType. ) are statically linked and therefore not needed during the wheel install.

Set up the conda environment. Note, if you want a qt backend, add pyqt to the list of conda packages.

Источник

Незамысловатый блог

09.08.2009

Пакет matplotlib. Установка, проверка, настройка

Введение

matplotlib — набор дополнительных модулей (библиотек) языка Python. Предоставляет средства для построения самых разнообразных 2D графиков и диаграмм данных. Достоинства. Отличается простотой использования — для построения весьма мудреных и красочно оформленных диаграмм достаточно нескольких строк кода. При этот качество получаемых изображений более чем достаточно для их публикования. Один из выходных формата файлов — Postscript, что, соответственно, позволяет вставлять изображения в документы TeX. Предоставляет API для встраивания своих графических объектов в приложения пользователя.

Установка

Официальный сайт проекта matplotlib. Дистрибутив для Windows можно заполучить на Sourceforge. Текущая версия 0.99.0, выпущена 06 августа 2009.

Для установки необходим, разумеется, сам Python и модуль NumPy. NumPy предоставляет методы для работы с огромными многомерными массивами. Дистрибутив для Windows так же можно взять на Sourceforge. Текущая версия 1.3.0 от 05 апреля 2009.

В Windows установка и matplotlib и NumPy не должна вызвать ни каких проблем. Скачиваем и запускаем файл дистрибутива.

Проверка

После установки проверяем работоспособность. Запускаем консоль Python, вводим:

В результате должно появиться вот такое окно диаграммы:

Что было сделано? Из пакета matplotlib импортирован модуль pyplot под именем plt . Модуль pyplot содержит функции (похожие на команды) создания диаграмм и изменения свойств их элементов. Функция plot() строит прямоугольные двумерные диаграммы (графики) в координатах X — Y. Если функции plot передан один аргумент (в нашем случае — список [1,2,3] ), она рассматривает его как совокупность значений откладываемых по оси Y, тогда по оси X ему будет соответствовать автоматически сгенерированный набор чисел 0,1,2. N — 1 , где N — число элементов в переданном списке. Функция title() задает заголовок диаграммы, а функция show() выводит интерактивное окно диаграммы. В общем все очень просто. Вот только вместо заголовка диаграммы «Прямая линия» 11 прямоугольников, не настроенный matplotlib не может найти шрифты с кириллическими символами.

Настройка

Пакет matplotlib можно легко настроить через конфигурационный файл matplotlibrc . Если Python установлен в папку C:\Python26\ файл matplotlibrc находится в папке: C:\Python26\Lib\site-packages\matplotlib\mpl-data\ . Вносить изменения можно прямо здесь, но лучше скопировать файл в папку пользователя: C:\Documents and Settings\UserName\.matplotlib\ , иначе при переустановке пакета конфигурационный файл будет перезаписан. Параметры пакета задаются в файле в виде пар свойство : значение , символ # отделяет комментарий. Свойство font.family определяет тип активного шрифта по умолчанию, может принимать пять значений: serif , sans-serif , cursive , fantasy , monospace . В свою очередь свойства font.serif , font.sans-serif , font.cursive , font.fantasy , font.monospace содержат списки имен шрифтов (через запятую, в порядке уменьшения приоритета) соответствующих каждому типу. Для «русификации» matplotlib необходимо изменить имена шрифтов в списке, на имена доступных в системе шрифтов, содержащих кириллические символы. Например так:

Для корректного отображения кириллических символов так же необходимо внести небольшие изменения в код программы. Все строки, содержащие символы национальных алфавитов должны быть типа unicode . Тип строкового литерала необходимо указать явно.

В случае скрипта исходный файл должен быть в кодировке UTF-8 . Кодировку файла так же следует указать явно. Для этого в первых строках программы пишем:

Вносим изменения в файл matplotlibrc , повторяем ввод в консоле Python:

Ну вот теперь подписи диаграммы отображаются корректно:

Функции pyplot.xlabel() , pyplot.ylabel() , как легко догадаться по названию, устанавливают подписи к осям X и Y соответственно.

Пакет matplotlib можно настраивать и динамически (во время выполнения программы). В пакете определена структура matplotlib.rcParams , с которой работают как со словарем. Ключевые слова в данном случае — имена свойств файла matplotlibrc .

Настройки шрифтов через matplotlib.rcParams можно изменить например так:

В результате должно получиться вот что:

Функции pyplot.plot() можно передать произвольное число пар аргументов типов list или array (тип array определен в модуле numpy). В примере выше передана одна пара: [1,2,3,4] , [1,4,9,16] . Первый элемент каждой пары функция рассматривает как значения откладываемые по оси X, второй элемент как значения по оси Y. Соответственно для каждой пары элементов строиться своя кривая на диаграмме. После каждой пары данных может быть передан дополнительный аргумент типа string — строка форматирования, которая определяет внешний вид кривой. Формат строки позаимствован из системы Matlab. Строка включает три подстроки. Первая подстрока задает цвет графического элемента, вторая стиль маркера, третья стиль линии. В примере ‘ ro’ = ‘r’ + ‘o’ , где ‘r’ — красный, ‘o’ — кружок. По умолчанию ‘b-‘ — синяя непрерывная линия.

Немного о назначении кнопок интерактивного окна диаграммы.

(pan/zoom) предназначена для прокрутки/масштабирования диаграммы. Нажимаем на кнопку, указатель мыши приобретает вид перекрещенных стрелок. Если двигать мышь и удерживать левую кнопку — диаграмма будет прокручиваться по направлению движения указателя. Если двигать мышь и удерживать правую кнопку — масштаб диаграммы будет изменяться, при движении вверх/вправо — уменьшаться, вниз/влево — увеличиваться. При нажатых клавишах » x » и » y » перемещение/масштабирование диаграммы будет происходить по осям X и Y соответственно, при нажатой клавише Ctrl диаграмма будет изменяться так, чтобы сохранились её пропорции (aspect ratio).

при нажатии включает режим прямоугольного масштабирования. Если нажать на кнопку указатель мыши приобретет вид креста. При нажатой левой кнопки мыши на диаграмме можно выделить прямоугольную область. После освобождения кнопки масштаб диаграммы будет изменен так, чтобы выделенная область заняла как можно большую площадь диаграммы.

позволяют перемещаться по истории изменения диаграммы. Все изменения вносимые в диаграмму пользователем (масштабирование, прокрутка) запоминаются. Кнопки со стрелками позволяют перемещаться вперед/назад по имеющимся вариантам диаграммы. Кнопка с домиком возвращает диаграмму к исходному состоянию.

вызывает стандартный для системы диалог сохранения файла. Позволяет сохранить диаграмму в файл. Можно выбрать следующие форматы файла диаграммы: png , pdf , svg , eps , ps . К сожалению не работает сохранение в формате emf (модуль pyemf разработчиком больше не поддерживается). Через формат emf было очень удобно вставлять диаграммы в документы Word.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

  • Python launcher for windows
  • Python kivy установка windows
  • Python keras установка под windows
  • Python import serial windows
  • Python import requests windows