matplotlib pyplot plot параметры

Pyplot tutorial¶

An introduction to the pyplot interface.

Intro to pyplot¶

matplotlib.pyplot is a collection of functions that make matplotlib work like MATLAB. Each pyplot function makes some change to a figure: e.g., creates a figure, creates a plotting area in a figure, plots some lines in a plotting area, decorates the plot with labels, etc.

In matplotlib.pyplot various states are preserved across function calls, so that it keeps track of things like the current figure and plotting area, and the plotting functions are directed to the current axes (please note that «axes» here and in most places in the documentation refers to the axes part of a figure and not the strict mathematical term for more than one axis).

the pyplot API is generally less-flexible than the object-oriented API. Most of the function calls you see here can also be called as methods from an Axes object. We recommend browsing the tutorials and examples to see how this works.

Generating visualizations with pyplot is very quick:

matplotlib pyplot plot параметры. Смотреть фото matplotlib pyplot plot параметры. Смотреть картинку matplotlib pyplot plot параметры. Картинка про matplotlib pyplot plot параметры. Фото matplotlib pyplot plot параметры

plot is a versatile function, and will take an arbitrary number of arguments. For example, to plot x versus y, you can write:

matplotlib pyplot plot параметры. Смотреть фото matplotlib pyplot plot параметры. Смотреть картинку matplotlib pyplot plot параметры. Картинка про matplotlib pyplot plot параметры. Фото matplotlib pyplot plot параметры

Formatting the style of your plot¶

For every x, y pair of arguments, there is an optional third argument which is the format string that indicates the color and line type of the plot. The letters and symbols of the format string are from MATLAB, and you concatenate a color string with a line style string. The default format string is ‘b-‘, which is a solid blue line. For example, to plot the above with red circles, you would issue

matplotlib pyplot plot параметры. Смотреть фото matplotlib pyplot plot параметры. Смотреть картинку matplotlib pyplot plot параметры. Картинка про matplotlib pyplot plot параметры. Фото matplotlib pyplot plot параметры

See the plot documentation for a complete list of line styles and format strings. The axis function in the example above takes a list of [xmin, xmax, ymin, ymax] and specifies the viewport of the axes.

If matplotlib were limited to working with lists, it would be fairly useless for numeric processing. Generally, you will use numpy arrays. In fact, all sequences are converted to numpy arrays internally. The example below illustrates plotting several lines with different format styles in one function call using arrays.

matplotlib pyplot plot параметры. Смотреть фото matplotlib pyplot plot параметры. Смотреть картинку matplotlib pyplot plot параметры. Картинка про matplotlib pyplot plot параметры. Фото matplotlib pyplot plot параметры

Plotting with keyword strings¶

Matplotlib allows you provide such an object with the data keyword argument. If provided, then you may generate plots with the strings corresponding to these variables.

matplotlib pyplot plot параметры. Смотреть фото matplotlib pyplot plot параметры. Смотреть картинку matplotlib pyplot plot параметры. Картинка про matplotlib pyplot plot параметры. Фото matplotlib pyplot plot параметры

Plotting with categorical variables¶

It is also possible to create a plot using categorical variables. Matplotlib allows you to pass categorical variables directly to many plotting functions. For example:

matplotlib pyplot plot параметры. Смотреть фото matplotlib pyplot plot параметры. Смотреть картинку matplotlib pyplot plot параметры. Картинка про matplotlib pyplot plot параметры. Фото matplotlib pyplot plot параметры

Controlling line properties¶

Here are the available Line2D properties.

To get a list of settable line properties, call the setp function with a line or lines as argument

Working with multiple figures and axes¶

matplotlib pyplot plot параметры. Смотреть фото matplotlib pyplot plot параметры. Смотреть картинку matplotlib pyplot plot параметры. Картинка про matplotlib pyplot plot параметры. Фото matplotlib pyplot plot параметры

You can create multiple figures by using multiple figure calls with an increasing figure number. Of course, each figure can contain as many axes and subplots as your heart desires:

Working with text¶

matplotlib pyplot plot параметры. Смотреть фото matplotlib pyplot plot параметры. Смотреть картинку matplotlib pyplot plot параметры. Картинка про matplotlib pyplot plot параметры. Фото matplotlib pyplot plot параметры

All of the text functions return a matplotlib.text.Text instance. Just as with lines above, you can customize the properties by passing keyword arguments into the text functions or using setp :

Using mathematical expressions in text¶

matplotlib accepts TeX equation expressions in any text expression. For example to write the expression \(\sigma_i=15\) in the title, you can write a TeX expression surrounded by dollar signs:

Annotating text¶

matplotlib pyplot plot параметры. Смотреть фото matplotlib pyplot plot параметры. Смотреть картинку matplotlib pyplot plot параметры. Картинка про matplotlib pyplot plot параметры. Фото matplotlib pyplot plot параметры

Logarithmic and other nonlinear axes¶

matplotlib.pyplot supports not only linear axis scales, but also logarithmic and logit scales. This is commonly used if data spans many orders of magnitude. Changing the scale of an axis is easy:

An example of four plots with the same data and different scales for the y axis is shown below.

matplotlib pyplot plot параметры. Смотреть фото matplotlib pyplot plot параметры. Смотреть картинку matplotlib pyplot plot параметры. Картинка про matplotlib pyplot plot параметры. Фото matplotlib pyplot plot параметры

It is also possible to add your own scale, see Developer’s guide for creating scales and transformations for details.

Total running time of the script: ( 0 minutes 3.758 seconds)

Keywords: matplotlib code example, codex, python plot, pyplot Gallery generated by Sphinx-Gallery

Источник

matplotlib.pyplot.plot¶

Plot y versus x as lines and/or markers.

The coordinates of the points or line nodes are given by x, y.

The optional parameter fmt is a convenient way for defining basic formatting like color, marker and linestyle. It’s a shortcut string notation described in the Notes section below.

You can use Line2D properties as keyword arguments for more control on the appearance. Line properties and fmt can be mixed. The following two calls yield identical results:

When conflicting with fmt, keyword arguments take precedence.

Plotting labelled data

There’s a convenient way for plotting objects with labelled data (i.e. data that can be accessed by index obj[‘y’] ). Instead of giving the data in x and y, you can provide the object in the data parameter and just give the labels for x and y:

Plotting multiple sets of data

There are various ways to plot multiple sets of data.

The most straight forward way is just to call plot multiple times. Example:

If x and/or y are 2D arrays a separate data set will be drawn for every column. If both x and y are 2D, they must have the same shape. If only one of them is 2D with shape (N, m) the other must have length N and will be used for every data set m.

The third way is to specify multiple sets of [x], y, [fmt] groups:

In this case, any additional keyword argument applies to all datasets. Also this syntax cannot be combined with the data parameter.

By default, each line is assigned a different style specified by a ‘style cycle’. The fmt and line property parameters are only necessary if you want explicit deviations from these defaults. Alternatively, you can also change the style cycle using rcParams[«axes.prop_cycle»] (default: cycler(‘color’, [‘#1f77b4’, ‘#ff7f0e’, ‘#2ca02c’, ‘#d62728’, ‘#9467bd’, ‘#8c564b’, ‘#e377c2’, ‘#7f7f7f’, ‘#bcbd22’, ‘#17becf’]) ).

Commonly, these parameters are 1D arrays.

They can also be scalars, or two-dimensional (in that case, the columns represent separate data sets).

These arguments cannot be passed as keywords.

fmt str, optional

A format string, e.g. ‘ro’ for red circles. See the Notes section for a full description of the format strings.

Format strings are just an abbreviation for quickly setting basic line properties. All of these and more can also be controlled by keyword arguments.

This argument cannot be passed as keyword.

data indexable object, optional

An object with labelled data. If given, provide the label names to plot in x and y.

A list of lines representing the plotted data.

Other Parameters:scalex, scaley bool, default: True

**kwargs Line2D properties, optional

kwargs are used to specify properties like a line label (for auto legends), linewidth, antialiasing, marker face color. Example:

If you specify multiple lines with one plot call, the kwargs apply to all those lines. In case the label object is iterable, each element is used as labels for each set of data.

Here is a list of available Line2D properties:

PropertyDescription
agg_filtera filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alphascalar or None
animatedbool
antialiased or aabool
clip_box Bbox
clip_onbool
clip_pathPatch or (Path, Transform) or None
color or ccolor
containsunknown
dash_capstyle CapStyle or
dash_joinstyle JoinStyle or
dashessequence of floats (on/off ink in points) or (None, None)
data(2, N) array or two 1D arrays
drawstyle or ds<'default', 'steps', 'steps-pre', 'steps-mid', 'steps-post'>, default: ‘default’
figure Figure
fillstyle
gidstr
in_layoutbool
labelobject
linestyle or ls
linewidth or lwfloat
markermarker style string, Path or MarkerStyle
markeredgecolor or meccolor
markeredgewidth or mewfloat
markerfacecolor or mfccolor
markerfacecoloralt or mfcaltcolor
markersize or msfloat
markeveryNone or int or (int, int) or slice or list[int] or float or (float, float) or list[bool]
path_effects AbstractPathEffect
pickerfloat or callable[[Artist, Event], tuple[bool, dict]]
pickradiusfloat
rasterizedbool
sketch_params(scale: float, length: float, randomness: float)
snapbool or None
solid_capstyle CapStyle or
solid_joinstyle JoinStyle or
transform matplotlib.transforms.Transform
urlstr
visiblebool
xdata1D array
ydata1D array
zorderfloat

scatter XY scatter plot with markers of varying size and/or color ( sometimes also called bubble chart).

Format Strings

A format string consists of a part for color, marker and line:

Other combinations such as [color][marker][line] are also supported, but note that their parsing may be ambiguous.

Markers

characterdescription
‘.’point marker
‘,’pixel marker
‘o’circle marker
‘v’triangle_down marker
‘^’triangle_up marker
triangle_left marker
‘>’triangle_right marker
‘1’tri_down marker
‘2’tri_up marker
‘3’tri_left marker
‘4’tri_right marker
‘8’octagon marker
‘s’square marker
‘p’pentagon marker
‘P’plus (filled) marker
‘*’star marker
‘h’hexagon1 marker
‘H’hexagon2 marker
‘+’plus marker
‘x’x marker
‘X’x (filled) marker
‘D’diamond marker
‘d’thin_diamond marker
‘|’vline marker
‘_’hline marker

Line Styles

characterdescription
‘-‘solid line style
‘—‘dashed line style
‘-.’dash-dot line style
‘:’dotted line style

Example format strings:

Colors

The supported color abbreviations are the single letter codes

charactercolor
‘b’blue
‘g’green
‘r’red
‘c’cyan
‘m’magenta
‘y’yellow
‘k’black
‘w’white

and the ‘CN’ colors that index into the default property cycle.

Источник

Matplotlib. Урок 2. Работа с инструментом pyplot

Основы работы с pyplot

Построение графиков

В результате будет выведено пустое поле:

matplotlib pyplot plot параметры. Смотреть фото matplotlib pyplot plot параметры. Смотреть картинку matplotlib pyplot plot параметры. Картинка про matplotlib pyplot plot параметры. Фото matplotlib pyplot plot параметры

Если в качестве параметра функции plot() передать список, то значения из этого списка будут отложены по оси ординат (ось y ), а по оси абсцисс (ось x ) будут отложены индексы элементов массива:

matplotlib pyplot plot параметры. Смотреть фото matplotlib pyplot plot параметры. Смотреть картинку matplotlib pyplot plot параметры. Картинка про matplotlib pyplot plot параметры. Фото matplotlib pyplot plot параметры

Для того, чтобы задать значения по осям x и y необходимо в plot() передать два списка:

matplotlib pyplot plot параметры. Смотреть фото matplotlib pyplot plot параметры. Смотреть картинку matplotlib pyplot plot параметры. Картинка про matplotlib pyplot plot параметры. Фото matplotlib pyplot plot параметры

Текстовые надписи на графике

Наиболее часто используемые текстовые надписи на графике это:

Рассмотрим кратко данные элементы, более подробный рассказ о них будет в одном из ближайших уроков.

Наименование осей

Для функций xlabel()/ylabel() основными являются следующие аргументы:

Аргументов у этих функций довольно много и они позволяют достаточно тонко настроить внешний вид надписей. В рамках этого урока мы только начинаем знакомиться с инструментом pyplot поэтому не будем приводить весь список.

Заголовок графика

Для задания заголовка графика используется функция title() :

Из параметров отметим следующие:

Текстовое примечание

Легенда

Разместим на уже знакомом нам графике необходимый набор подписей.

matplotlib pyplot plot параметры. Смотреть фото matplotlib pyplot plot параметры. Смотреть картинку matplotlib pyplot plot параметры. Картинка про matplotlib pyplot plot параметры. Фото matplotlib pyplot plot параметры

Работа с линейным графиком

В этом параграфе мы рассмотрим основные параметры и способы их задания для изменения внешнего вида линейного графика. Matplotlib предоставляет огромное количество инструментов для построения различных видов графиков. Так как наиболее часто встречающийся вид графика – это линейный, ему и уделим внимание. Необходимо помнить, что настройка графиков других видов, будет осуществляться сходным образом.

Параметры, которые отвечают за отображение графика можно задать непосредственно в самой функции plot() :

Стиль линии графика

Значение параметраОписание
‘-‘ или ‘solid’Непрерывная линия
‘–‘ или ‘dashed’Штриховая линия
‘-.’ или ‘dashdot’Штрихпунктирная линия
‘:’ или ‘dotted’Пунктирная линия
‘None’ или ‘ ‘ или ”Не отображать линию

matplotlib pyplot plot параметры. Смотреть фото matplotlib pyplot plot параметры. Смотреть картинку matplotlib pyplot plot параметры. Картинка про matplotlib pyplot plot параметры. Фото matplotlib pyplot plot параметры

Либо можно воспользоваться функцией setp() :

Результат будет тот же, что на рисунке выше.

matplotlib pyplot plot параметры. Смотреть фото matplotlib pyplot plot параметры. Смотреть картинку matplotlib pyplot plot параметры. Картинка про matplotlib pyplot plot параметры. Фото matplotlib pyplot plot параметры

Тот же результат можно получить, вызвав plot() для построения каждого графика по отдельности. Если вы хотите представить каждый график отдельно на своем поле, то используйте для этого subplot() (см. Размещение графиков на разных полях)

Цвет линии

Например штриховая красная линия будет задаваться так: ‘–r’, а штрих пунктирная зеленая так ‘-.g’

matplotlib pyplot plot параметры. Смотреть фото matplotlib pyplot plot параметры. Смотреть картинку matplotlib pyplot plot параметры. Картинка про matplotlib pyplot plot параметры. Фото matplotlib pyplot plot параметры

Тип графика

До этого момента мы работали только с линейными графиками, функция plot() позволяет задать тип графика: линейный либо точечный, при этом для точечного графика можно указать соответствующий маркер. Приведем пару примеров:

matplotlib pyplot plot параметры. Смотреть фото matplotlib pyplot plot параметры. Смотреть картинку matplotlib pyplot plot параметры. Картинка про matplotlib pyplot plot параметры. Фото matplotlib pyplot plot параметры

matplotlib pyplot plot параметры. Смотреть фото matplotlib pyplot plot параметры. Смотреть картинку matplotlib pyplot plot параметры. Картинка про matplotlib pyplot plot параметры. Фото matplotlib pyplot plot параметры

Размер маркера можно менять, об этом более подробно будет рассмотрено в уроке, посвященном точечным графикам.

Размещение графиков на разных полях

Существуют три основных подхода к размещению нескольких графиков на разных полях:

В этом уроке будут рассмотрены первые два подхода.

Работа с функцией subplot()

После задания размера, указывается местоположение, куда будет установлено поле с графиком с помощью функции subplot(). Чаще всего используют следующие варианты вызова subplot:

subplot(nrows, ncols, index)

Рассмотрим на примере работу с данными функциями:

matplotlib pyplot plot параметры. Смотреть фото matplotlib pyplot plot параметры. Смотреть картинку matplotlib pyplot plot параметры. Картинка про matplotlib pyplot plot параметры. Фото matplotlib pyplot plot параметры

Второй вариант использования subplot():

Работа с функцией subplots()

Решим задачу вывода четырех графиков с помощью функции subplots() :

Результат будет аналогичный тому, что приведен в разделе “Работа с функцией subplot() ”.

P.S.

Источник

matplotlib.pyplot ¶

Pyplot function overview¶

Colors in Matplotlib¶

There are many colormaps you can use to map data onto color values. Below we list several ways in which color can be utilized in Matplotlib.

For a more in-depth look at colormaps, see the Choosing Colormaps in Matplotlib tutorial.

You can set the colormap for an image, pcolor, scatter, etc, using a keyword argument:

or using the set_cmap() function:

In interactive mode, set_cmap() will update the colormap post-hoc, allowing you to see which one works best for your data.

There are several common color schemes used in visualization:

Sequential schemes for unipolar data that progresses from low to high Diverging schemes for bipolar data that emphasizes positive or negative deviations from a central value Cyclic schemes for plotting values that wrap around at the endpoints, such as phase angle, wind direction, or time of day Qualitative schemes for nominal data that has no inherent ordering, where color is used only to distinguish categories

Matplotlib ships with 4 perceptually uniform colormaps which are the recommended colormaps for sequential data:

ColormapDescription
infernoperceptually uniform shades of black-red-yellow
magmaperceptually uniform shades of black-red-white
plasmaperceptually uniform shades of blue-red-yellow
viridisperceptually uniform shades of blue-green-yellow

The following colormaps are based on the ColorBrewer color specifications and designs developed by Cynthia Brewer:

ColorBrewer Diverging (luminance is highest at the midpoint, and decreases towards differently-colored endpoints):

ColormapDescription
BrBGbrown, white, blue-green
PiYGpink, white, yellow-green
PRGnpurple, white, green
PuOrorange, white, purple
RdBured, white, blue
RdGyred, white, gray
RdYlBured, yellow, blue
RdYlGnred, yellow, green
Spectralred, orange, yellow, green, blue

ColorBrewer Sequential (luminance decreases monotonically):

ColormapDescription
Blueswhite to dark blue
BuGnwhite, light blue, dark green
BuPuwhite, light blue, dark purple
GnBuwhite, light green, dark blue
Greenswhite to dark green
Greyswhite to black (not linear)
Orangeswhite, orange, dark brown
OrRdwhite, orange, dark red
PuBuwhite, light purple, dark blue
PuBuGnwhite, light purple, dark green
PuRdwhite, light purple, dark red
Purpleswhite to dark purple
RdPuwhite, pink, dark purple
Redswhite to dark red
YlGnlight yellow, dark green
YlGnBulight yellow, light green, dark blue
YlOrBrlight yellow, orange, dark brown
YlOrRdlight yellow, orange, dark red

A set of colormaps derived from those of the same name provided with Matlab are also included:

A set of palettes from the Yorick scientific visualisation package, an evolution of the GIST package, both by David H. Munro are included:

ColormapDescription
gist_earthmapmaker’s colors from dark blue deep ocean to green lowlands to brown highlands to white mountains
gist_heatsequential increasing black-red-orange-white, to emulate blackbody radiation from an iron bar as it grows hotter
gist_ncarpseudo-spectral black-blue-green-yellow-red-purple-white colormap from National Center for Atmospheric Research [2]
gist_rainbowruns through the colors in spectral order from red to violet at full saturation (like hsv but not cyclic)
gist_stern«Stern special» color table from Interactive Data Language software

A set of cyclic colormaps:

ColormapDescription
hsvred-yellow-green-cyan-blue-magenta-red, formed by changing the hue component in the HSV color space
twilightperceptually uniform shades of white-blue-black-red-white
twilight_shiftedperceptually uniform shades of black-blue-white-red-black

Other miscellaneous schemes:

ColormapDescription
afmhotsequential black-orange-yellow-white blackbody spectrum, commonly used in atomic force microscopy
brgblue-red-green
bwrdiverging blue-white-red
coolwarmdiverging blue-gray-red, meant to avoid issues with 3D shading, color blindness, and ordering of colors [3]
CMRmap«Default colormaps on color images often reproduce to confusing grayscale images. The proposed colormap maintains an aesthetically pleasing color image that automatically reproduces to a monotonic grayscale with discrete, quantifiable saturation levels.» [4]
cubehelixUnlike most other color schemes cubehelix was designed by D.A. Green to be monotonically increasing in terms of perceived brightness. Also, when printed on a black and white postscript printer, the scheme results in a greyscale with monotonically increasing brightness. This color scheme is named cubehelix because the (r, g, b) values produced can be visualised as a squashed helix around the diagonal in the (r, g, b) color cube.
gnuplotgnuplot’s traditional pm3d scheme (black-blue-red-yellow)
gnuplot2sequential color printable as gray (black-blue-violet-yellow-white)
oceangreen-blue-white
rainbowspectral purple-blue-green-yellow-orange-red colormap with diverging luminance
seismicdiverging blue-white-red
nipy_spectralblack-purple-blue-green-yellow-red-white spectrum, originally from the Neuroimaging in Python project
terrainmapmaker’s colors, blue-green-yellow-brown-white, originally from IGOR Pro
turboSpectral map (purple-blue-green-yellow-orange-red) with a bright center and darker endpoints. A smoother alternative to jet.

The following colormaps are redundant and may be removed in future versions. It’s recommended to use the names in the descriptions instead, which produce identical output:

Источник

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

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