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:
plot is a versatile function, and will take an arbitrary number of arguments. For example, to plot x versus y, you can write:
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
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.
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.
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:
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¶
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¶
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¶
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.
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.
**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:
Property | Description |
---|---|
agg_filter | a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array |
alpha | scalar or None |
animated | bool |
antialiased or aa | bool |
clip_box | Bbox |
clip_on | bool |
clip_path | Patch or (Path, Transform) or None |
color or c | color |
contains | unknown |
dash_capstyle | CapStyle or |
dash_joinstyle | JoinStyle or |
dashes | sequence 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 | |
gid | str |
in_layout | bool |
label | object |
linestyle or ls | |
linewidth or lw | float |
marker | marker style string, Path or MarkerStyle |
markeredgecolor or mec | color |
markeredgewidth or mew | float |
markerfacecolor or mfc | color |
markerfacecoloralt or mfcalt | color |
markersize or ms | float |
markevery | None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool] |
path_effects | AbstractPathEffect |
picker | float or callable[[Artist, Event], tuple[bool, dict]] |
pickradius | float |
rasterized | bool |
sketch_params | (scale: float, length: float, randomness: float) |
snap | bool or None |
solid_capstyle | CapStyle or |
solid_joinstyle | JoinStyle or |
transform | matplotlib.transforms.Transform |
url | str |
visible | bool |
xdata | 1D array |
ydata | 1D array |
zorder | float |
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
character | description |
---|---|
‘.’ | 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
character | description |
---|---|
‘-‘ | 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
character | color |
---|---|
‘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
Построение графиков
В результате будет выведено пустое поле:
Если в качестве параметра функции plot() передать список, то значения из этого списка будут отложены по оси ординат (ось y ), а по оси абсцисс (ось x ) будут отложены индексы элементов массива:
Для того, чтобы задать значения по осям x и y необходимо в plot() передать два списка:
Текстовые надписи на графике
Наиболее часто используемые текстовые надписи на графике это:
Рассмотрим кратко данные элементы, более подробный рассказ о них будет в одном из ближайших уроков.
Наименование осей
Для функций xlabel()/ylabel() основными являются следующие аргументы:
Аргументов у этих функций довольно много и они позволяют достаточно тонко настроить внешний вид надписей. В рамках этого урока мы только начинаем знакомиться с инструментом pyplot поэтому не будем приводить весь список.
Заголовок графика
Для задания заголовка графика используется функция title() :
Из параметров отметим следующие:
Текстовое примечание
Легенда
Разместим на уже знакомом нам графике необходимый набор подписей.
Работа с линейным графиком
В этом параграфе мы рассмотрим основные параметры и способы их задания для изменения внешнего вида линейного графика. Matplotlib предоставляет огромное количество инструментов для построения различных видов графиков. Так как наиболее часто встречающийся вид графика – это линейный, ему и уделим внимание. Необходимо помнить, что настройка графиков других видов, будет осуществляться сходным образом.
Параметры, которые отвечают за отображение графика можно задать непосредственно в самой функции plot() :
Стиль линии графика
Значение параметра | Описание |
‘-‘ или ‘solid’ | Непрерывная линия |
‘–‘ или ‘dashed’ | Штриховая линия |
‘-.’ или ‘dashdot’ | Штрихпунктирная линия |
‘:’ или ‘dotted’ | Пунктирная линия |
‘None’ или ‘ ‘ или ” | Не отображать линию |
Либо можно воспользоваться функцией setp() :
Результат будет тот же, что на рисунке выше.
Тот же результат можно получить, вызвав plot() для построения каждого графика по отдельности. Если вы хотите представить каждый график отдельно на своем поле, то используйте для этого subplot() (см. Размещение графиков на разных полях)
Цвет линии
Например штриховая красная линия будет задаваться так: ‘–r’, а штрих пунктирная зеленая так ‘-.g’
Тип графика
До этого момента мы работали только с линейными графиками, функция plot() позволяет задать тип графика: линейный либо точечный, при этом для точечного графика можно указать соответствующий маркер. Приведем пару примеров:
Размер маркера можно менять, об этом более подробно будет рассмотрено в уроке, посвященном точечным графикам.
Размещение графиков на разных полях
Существуют три основных подхода к размещению нескольких графиков на разных полях:
В этом уроке будут рассмотрены первые два подхода.
Работа с функцией subplot()
После задания размера, указывается местоположение, куда будет установлено поле с графиком с помощью функции subplot(). Чаще всего используют следующие варианты вызова subplot:
subplot(nrows, ncols, index)
Рассмотрим на примере работу с данными функциями:
Второй вариант использования 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:
Colormap | Description |
---|---|
inferno | perceptually uniform shades of black-red-yellow |
magma | perceptually uniform shades of black-red-white |
plasma | perceptually uniform shades of blue-red-yellow |
viridis | perceptually 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):
Colormap | Description |
---|---|
BrBG | brown, white, blue-green |
PiYG | pink, white, yellow-green |
PRGn | purple, white, green |
PuOr | orange, white, purple |
RdBu | red, white, blue |
RdGy | red, white, gray |
RdYlBu | red, yellow, blue |
RdYlGn | red, yellow, green |
Spectral | red, orange, yellow, green, blue |
ColorBrewer Sequential (luminance decreases monotonically):
Colormap | Description |
---|---|
Blues | white to dark blue |
BuGn | white, light blue, dark green |
BuPu | white, light blue, dark purple |
GnBu | white, light green, dark blue |
Greens | white to dark green |
Greys | white to black (not linear) |
Oranges | white, orange, dark brown |
OrRd | white, orange, dark red |
PuBu | white, light purple, dark blue |
PuBuGn | white, light purple, dark green |
PuRd | white, light purple, dark red |
Purples | white to dark purple |
RdPu | white, pink, dark purple |
Reds | white to dark red |
YlGn | light yellow, dark green |
YlGnBu | light yellow, light green, dark blue |
YlOrBr | light yellow, orange, dark brown |
YlOrRd | light 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:
Colormap | Description |
---|---|
gist_earth | mapmaker’s colors from dark blue deep ocean to green lowlands to brown highlands to white mountains |
gist_heat | sequential increasing black-red-orange-white, to emulate blackbody radiation from an iron bar as it grows hotter |
gist_ncar | pseudo-spectral black-blue-green-yellow-red-purple-white colormap from National Center for Atmospheric Research [2] |
gist_rainbow | runs 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:
Colormap | Description |
---|---|
hsv | red-yellow-green-cyan-blue-magenta-red, formed by changing the hue component in the HSV color space |
twilight | perceptually uniform shades of white-blue-black-red-white |
twilight_shifted | perceptually uniform shades of black-blue-white-red-black |
Other miscellaneous schemes:
Colormap | Description |
---|---|
afmhot | sequential black-orange-yellow-white blackbody spectrum, commonly used in atomic force microscopy |
brg | blue-red-green |
bwr | diverging blue-white-red |
coolwarm | diverging 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] |
cubehelix | Unlike 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. |
gnuplot | gnuplot’s traditional pm3d scheme (black-blue-red-yellow) |
gnuplot2 | sequential color printable as gray (black-blue-violet-yellow-white) |
ocean | green-blue-white |
rainbow | spectral purple-blue-green-yellow-orange-red colormap with diverging luminance |
seismic | diverging blue-white-red |
nipy_spectral | black-purple-blue-green-yellow-red-white spectrum, originally from the Neuroimaging in Python project |
terrain | mapmaker’s colors, blue-green-yellow-brown-white, originally from IGOR Pro |
turbo | Spectral 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: