Spec-Zone.ru › Matplotlib 3.2

matplotlib.quiver.Quiver

class matplotlib.quiver.Quiver(ax, *args, scale=None, headwidth=3, headlength=5, headaxislength=4.5, minshaft=1, minlength=1, units='width', scale_units=None, angles='uv', width=None, color='k', pivot='tail', **kw) [source]

Bases: matplotlib.collections.PolyCollection

Специализированный PolyCollection для стрелок.

Единственный API-метод — set_UVC(), который можно использовать для изменения размера, ориентации и цвета стрелок; их расположение фиксируется при создании класса. Возможно, этот метод будет полезен в анимациях.

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

Построение двумерного поля стрелок.

Вызов:

quiver([X, Y], U, V, [C], **kw)

Где X, Y определяют расположение стрелок, U, V определяют направления стрелок, а C необязательно задаёт цвет.

Размер стрелок

По умолчанию длина стрелок автоматически масштабируется до разумного размера. Чтобы изменить это поведение, см. параметры scale и scale_units.

Форма стрелок

Значения по умолчанию дают слегка загнутую стрелку; чтобы сделать головку треугольной, сделайте headaxislength равным headlength. Чтобы сделать стрелку более острой, уменьшите headwidth или увеличьте headlength и headaxislength. Чтобы сделать головку меньше по отношению к стволу, уменьшите все параметры головки. Вероятно, лучше всего оставить minshaft без изменений.

Контур стрелки

linewidths и edgecolors можно использовать для настройки контуров стрелок.

Параметры:
X, Y1D or 2D array-like, optional

Координаты x и y расположения стрелок.

Если не заданы, они будут сгенерированы как равномерная целочисленная сетка на основе размеров U и V.

Если X и Y одномерны, а U, V двумерны, X и Y расширяются до двумерных с помощью X, Y = np.meshgrid(X, Y). В этом случае len(X) и len(Y) должны соответствовать столбцам и строкам размеров U и V.

U, V1D or 2D array-like

Компоненты x и y направлений векторов стрелок.

Они должны иметь одинаковое количество элементов, соответствующее количеству расположений стрелок. U и V могут быть замаскированы. Будут нарисованы только те расположения, которые не замаскированы в U, V и C.

C1D or 2D array-like, optional

Числовые данные, которые определяют цвета стрелок с помощью сопоставления цветов по norm и cmap.

Это не поддерживает явные цвета. Если вы хотите задать цвета напрямую, используйте color вместо этого. Размер C должен соответствовать количеству расположений стрелок.

units{'width', 'height', 'dots', 'inches', 'x', 'y' 'xy'}, default: 'width'

Размеры стрелок (за исключением length) измеряются в кратных единицах.

Поддерживаются следующие значения:

  • 'width', 'height': Ширина или высота оси.
  • 'dots', 'inches': Пиксели или дюймы на основе разрешения фигуры.
  • 'x', 'y', 'xy': X, Y или \(\sqrt{X^2 + Y^2}\) в единицах данных.

Стрелки масштабируются по-разному в зависимости от единиц. Для 'x' или 'y' стрелки увеличиваются при приближении; для других единиц размер стрелки не зависит от состояния масштабирования. Для 'width' или 'height' размер стрелки увеличивается с шириной и высотой осей соответственно при изменении размера окна; для 'dots' или 'inches' изменение размера не влияет на стрелки.

angles{'uv', 'xy'} or array-like, optional, default: 'uv'

Метод определения угла стрелок.

  • 'uv': Соотношение сторон оси стрелки равно 1, так что если U == V, ориентация стрелки на графике составляет 45 градусов против часовой стрелки от горизонтальной оси (положительное направление вправо).

    Используйте это, если стрелки обозначают величину, которая не основана на координатах данных X, Y.

  • 'xy': Стрелки указывают от (x, y) к (x+u, y+v). Используйте это, например, для построения градиентного поля.
  • В качестве альтернативы, произвольные углы могут быть заданы явно как массив значений в градусах, против часовой стрелки от горизонтальной оси.

    В этом случае U, V используются только для определения длины стрелок.

Примечание: инвертирование оси данных будет соответственно инвертировать стрелки только с angles='xy'.

scalefloat, optional

Количество единиц данных на единицу длины стрелки, например, м/с на единицу ширины графика; меньший параметр scale делает стрелку длиннее. Значение по умолчанию — None.

Если None, используется простой алгоритм автоматического масштабирования на основе средней длины вектора и количества векторов. Единица длины стрелки задаётся параметром scale_units.

scale_units{'width', 'height', 'dots', 'inches', 'x', 'y', 'xy'}, optional

Если параметр scale равен None, единица длины стрелки. Значение по умолчанию — None.

Например, scale_units — 'inches', scale — 2.0, и (u, v) = (1, 0), то вектор будет длиной 0,5 дюйма.

Если scale_units — 'width' или 'height', то вектор будет равен половине ширины/высоты осей.

Если scale_units — 'x', то вектор будет равен 0,5 единиц оси x. Чтобы построить векторы на плоскости x-y, где u и v имеют те же единицы, что x и y, используйте angles='xy', scale_units='xy', scale=1.

widthfloat, optional

Ширина стержня стрелки в единицах стрелки; значение по умолчанию зависит от выбранных единиц, указанных выше, и количества векторов; типичное начальное значение составляет примерно 0,005 от ширины графика.

headwidthfloat, optional, default: 3

Ширина головки как кратная ширине стержня.

headlengthfloat, optional, default: 5

Длина головки как кратная ширине стержня.

headaxislengthfloat, optional, default: 4.5

Длина головки в точке пересечения со стволом.

minshaftfloat, optional, default: 1

Длина, ниже которой масштабируется стрелка, в единицах длины головки. Не устанавливайте это значение меньше 1, иначе маленькие стрелки будут выглядеть ужасно!

minlengthfloat, optional, default: 1

Минимальная длина как кратная ширине стержня; если длина стрелки меньше этого значения, вместо неё рисуется точка (шестиугольник) этого диаметра.

pivot{'tail', 'mid', 'middle', 'tip'}, optional, default: 'tail'

Часть стрелки, привязанная к сетке X, Y. Стрелка вращается вокруг этой точки.

'mid' — синоним 'middle'.

colorcolor or color sequence, optional

Явный цвет(а) для стрелок. Если C задан, color не имеет эффекта.

Это синоним параметра PolyCollection facecolor.

Другие параметры:
**kwargsPolyCollection properties, optional

Все остальные ключевые аргументы передаются в PolyCollection:

Свойство Описание
agg_filter функция фильтра, которая принимает (m, n, 3) массив чисел с плавающей точкой и значение dpi и возвращает (m, n, 3) массив
alpha число с плавающей точкой или None
animated булево значение
antialiased или aa или antialiaseds булево значение или последовательность булевых значений
array массив ndarray
capstyle {'butt', 'round', 'projecting'}
clim (vmin: число с плавающей точкой, vmax: число с плавающей точкой)
clip_box Bbox
clip_on булево значение
clip_path Объект Patch или (Путь, Преобразование) или None
cmap цветовая карта или зарегистрированное имя цветовой карты
color цвет или последовательность кортежей rgba
contains вызываемая функция
edgecolor или ec или edgecolors цвет или последовательность цветов или 'face'
facecolor или facecolors или fc цвет или последовательность цветов
figure Figure
gid строка
hatch {'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
in_layout булево значение
joinstyle {'miter', 'round', 'bevel'}
label объект
linestyle или dashes или linestyles или ls {'-', '--', '-.', ':', '', (смещение, последовательность вкл/выкл), ...}
linewidth или linewidths или lw число с плавающей точкой или последовательность чисел с плавающей точкой
norm Normalize
offset_position {'экран', 'данные'}
offsets последовательность (N, 2) или (2,)
path_effects AbstractPathEffect
picker None или булево значение или число с плавающей точкой или вызываемая функция
pickradius неизвестно
rasterized булево значение или None
sketch_params (масштаб: число с плавающей точкой, длина: число с плавающей точкой, случайность: число с плавающей точкой)
snap булево значение или None
transform Transform
url строка
urls Список строк или None
visible булево значение
zorder число с плавающей точкой

См. также

quiverkey
Добавить ключ к графику стрелок.
property color
draw(self, renderer) [source]

Отрисовка элемента Artist с помощью заданного рендерера.

Этот метод переопределяется в подклассах Artist. Обычно он реализуется так, чтобы не иметь никакого эффекта, если элемент Artist не видим (Artist.get_visible равен False).

Параметры:
rendererRendererBase subclass.
get_datalim(self, transData) [source]
property keytext
property keyvec
quiver_doc = "\nPlot a 2D field of arrows.\n\nCall signature::\n\n quiver([X, Y], U, V, [C], **kw)\n\nWhere *X*, *Y* define the arrow locations, *U*, *V* define the arrow\ndirections, and *C* optionally sets the color.\n\n**Arrow size**\n\nThe default settings auto-scales the length of the arrows to a reasonable size.\nTo change this behavior see the *scale* and *scale_units* parameters.\n\n**Arrow shape**\n\nThe defaults give a slightly swept-back arrow; to make the head a\ntriangle, make *headaxislength* the same as *headlength*. To make the\narrow more pointed, reduce *headwidth* or increase *headlength* and\n*headaxislength*. To make the head smaller relative to the shaft,\nscale down all the head parameters. You will probably do best to leave\nminshaft alone.\n\n**Arrow outline**\n\n*linewidths* and *edgecolors* can be used to customize the arrow\noutlines.\n\nParameters\n----------\nX, Y : 1D or 2D array-like, optional\n The x and y coordinates of the arrow locations.\n\n If not given, they will be generated as a uniform integer meshgrid based\n on the dimensions of *U* and *V*.\n\n If *X* and *Y* are 1D but *U*, *V* are 2D, *X*, *Y* are expanded to 2D\n using ``X, Y = np.meshgrid(X, Y)``. In this case ``len(X)`` and ``len(Y)``\n must match the column and row dimensions of *U* and *V*.\n\nU, V : 1D or 2D array-like\n The x and y direction components of the arrow vectors.\n\n They must have the same number of elements, matching the number of arrow\n locations. *U* and *V* may be masked. Only locations unmasked in\n *U*, *V*, and *C* will be drawn.\n\nC : 1D or 2D array-like, optional\n Numeric data that defines the arrow colors by colormapping via *norm* and\n *cmap*.\n\n This does not support explicit colors. If you want to set colors directly,\n use *color* instead. The size of *C* must match the number of arrow\n locations.\n\nunits : {'width', 'height', 'dots', 'inches', 'x', 'y' 'xy'}, default: 'width'\n The arrow dimensions (except for *length*) are measured in multiples of\n this unit.\n\n The following values are supported:\n\n - 'width', 'height': The width or height of the axis.\n - 'dots', 'inches': Pixels or inches based on the figure dpi.\n - 'x', 'y', 'xy': *X*, *Y* or :math:`\\sqrt{X^2 + Y^2}` in data units.\n\n The arrows scale differently depending on the units. For\n 'x' or 'y', the arrows get larger as one zooms in; for other\n units, the arrow size is independent of the zoom state. For\n 'width or 'height', the arrow size increases with the width and\n height of the axes, respectively, when the window is resized;\n for 'dots' or 'inches', resizing does not change the arrows.\n\nangles : {'uv', 'xy'} or array-like, optional, default: 'uv'\n Method for determining the angle of the arrows.\n\n - 'uv': The arrow axis aspect ratio is 1 so that\n if *U* == *V* the orientation of the arrow on the plot is 45 degrees\n counter-clockwise from the horizontal axis (positive to the right).\n\n Use this if the arrows symbolize a quantity that is not based on\n *X*, *Y* data coordinates.\n\n - 'xy': Arrows point from (x, y) to (x+u, y+v).\n Use this for plotting a gradient field, for example.\n\n - Alternatively, arbitrary angles may be specified explicitly as an array\n of values in degrees, counter-clockwise from the horizontal axis.\n\n In this case *U*, *V* is only used to determine the length of the\n arrows.\n\n Note: inverting a data axis will correspondingly invert the\n arrows only with ``angles='xy'``.\n\nscale : float, optional\n Number of data units per arrow length unit, e.g., m/s per plot width; a\n smaller scale parameter makes the arrow longer. Default is *None*.\n\n If *None*, a simple autoscaling algorithm is used, based on the average\n vector length and the number of vectors. The arrow length unit is given by\n the *scale_units* parameter.\n\nscale_units : {'width', 'height', 'dots', 'inches', 'x', 'y', 'xy'}, optional\n If the *scale* kwarg is *None*, the arrow length unit. Default is *None*.\n\n e.g. *scale_units* is 'inches', *scale* is 2.0, and ``(u, v) = (1, 0)``,\n then the vector will be 0.5 inches long.\n\n If *scale_units* is 'width' or 'height', then the vector will be half the\n width/height of the axes.\n\n If *scale_units* is 'x' then the vector will be 0.5 x-axis\n units. To plot vectors in the x-y plane, with u and v having\n the same units as x and y, use\n ``angles='xy', scale_units='xy', scale=1``.\n\nwidth : float, optional\n Shaft width in arrow units; default depends on choice of units,\n above, and number of vectors; a typical starting value is about\n 0.005 times the width of the plot.\n\nheadwidth : float, optional, default: 3\n Head width as multiple of shaft width.\n\nheadlength : float, optional, default: 5\n Head length as multiple of shaft width.\n\nheadaxislength : float, optional, default: 4.5\n Head length at shaft intersection.\n\nminshaft : float, optional, default: 1\n Length below which arrow scales, in units of head length. Do not\n set this to less than 1, or small arrows will look terrible!\n\nminlength : float, optional, default: 1\n Minimum length as a multiple of shaft width; if an arrow length\n is less than this, plot a dot (hexagon) of this diameter instead.\n\npivot : {'tail', 'mid', 'middle', 'tip'}, optional, default: 'tail'\n The part of the arrow that is anchored to the *X*, *Y* grid. The arrow\n rotates about this point.\n\n 'mid' is a synonym for 'middle'.\n\ncolor : color or color sequence, optional\n Explicit color(s) for the arrows. If *C* has been set, *color* has no\n effect.\n\n This is a synonym for the `~.PolyCollection` *facecolor* parameter.\n\nOther Parameters\n----------------\n**kwargs : `~matplotlib.collections.PolyCollection` properties, optional\n All other keyword arguments are passed on to `.PolyCollection`:\n\n \n .. table::\n :class: property-table\n\n ================================================================================================= =====================================================================================================\n Property Description \n ================================================================================================= =====================================================================================================\n :meth:`agg_filter <matplotlib.artist.Artist.set_agg_filter>` a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array\n :meth:`alpha <matplotlib.collections.Collection.set_alpha>` float or None \n :meth:`animated <matplotlib.artist.Artist.set_animated>` bool \n :meth:`antialiased <matplotlib.collections.Collection.set_antialiased>` or aa or antialiaseds bool or sequence of bools \n :meth:`array <matplotlib.cm.ScalarMappable.set_array>` ndarray \n :meth:`capstyle <matplotlib.collections.Collection.set_capstyle>` {'butt', 'round', 'projecting'} \n :meth:`clim <matplotlib.cm.ScalarMappable.set_clim>` (vmin: float, vmax: float) \n :meth:`clip_box <matplotlib.artist.Artist.set_clip_box>` `.Bbox` \n :meth:`clip_on <matplotlib.artist.Artist.set_clip_on>` bool \n :meth:`clip_path <matplotlib.artist.Artist.set_clip_path>` Patch or (Path, Transform) or None \n :meth:`cmap <matplotlib.cm.ScalarMappable.set_cmap>` colormap or registered colormap name \n :meth:`color <matplotlib.collections.Collection.set_color>` color or sequence of rgba tuples \n :meth:`contains <matplotlib.artist.Artist.set_contains>` callable \n :meth:`edgecolor <matplotlib.collections.Collection.set_edgecolor>` or ec or edgecolors color or sequence of colors or 'face' \n :meth:`facecolor <matplotlib.collections.Collection.set_facecolor>` or facecolors or fc color or sequence of colors \n :meth:`figure <matplotlib.artist.Artist.set_figure>` `.Figure` \n :meth:`gid <matplotlib.artist.Artist.set_gid>` str \n :meth:`hatch <matplotlib.collections.Collection.set_hatch>` {'/', '\\\\', '|', '-', '+', 'x', 'o', 'O', '.', '*'} \n :meth:`in_layout <matplotlib.artist.Artist.set_in_layout>` bool \n :meth:`joinstyle <matplotlib.collections.Collection.set_joinstyle>` {'miter', 'round', 'bevel'} \n :meth:`label <matplotlib.artist.Artist.set_label>` object \n :meth:`linestyle <matplotlib.collections.Collection.set_linestyle>` or dashes or linestyles or ls {'-', '--', '-.', ':', '', (offset, on-off-seq), ...} \n :meth:`linewidth <matplotlib.collections.Collection.set_linewidth>` or linewidths or lw float or sequence of floats \n :meth:`norm <matplotlib.cm.ScalarMappable.set_norm>` `.Normalize` \n :meth:`offset_position <matplotlib.collections.Collection.set_offset_position>` {'screen', 'data'} \n :meth:`offsets <matplotlib.collections.Collection.set_offsets>` array-like (N, 2) or (2,) \n :meth:`path_effects <matplotlib.artist.Artist.set_path_effects>` `.AbstractPathEffect` \n :meth:`picker <matplotlib.artist.Artist.set_picker>` None or bool or float or callable \n :meth:`pickradius <matplotlib.collections.Collection.set_pickradius>` unknown \n :meth:`rasterized <matplotlib.artist.Artist.set_rasterized>` bool or None \n :meth:`sketch_params <matplotlib.artist.Artist.set_sketch_params>` (scale: float, length: float, randomness: float) \n :meth:`snap <matplotlib.artist.Artist.set_snap>` bool or None \n :meth:`transform <matplotlib.artist.Artist.set_transform>` `.Transform` \n :meth:`url <matplotlib.artist.Artist.set_url>` str \n :meth:`urls <matplotlib.collections.Collection.set_urls>` List[str] or None \n :meth:`visible <matplotlib.artist.Artist.set_visible>` bool \n :meth:`zorder <matplotlib.artist.Artist.set_zorder>` float \n ================================================================================================= =====================================================================================================\n\n\nSee Also\n--------\nquiverkey : Add a key to a quiver plot.\n"
remove(self) [source]

Перегрузка метода remove

set_UVC(self, U, V, C=None) [source]

Примеры использования matplotlib.quiver.Quiver

Advanced quiver and quiverkey functions

Расширенные функции quiver и quiverkey

Quiver Simple Demo

Простой пример quiver

© 2012–2018 Matplotlib Development Team. All rights reserved.
Licensed under the Matplotlib License Agreement.
https://matplotlib.org/3.2.2/api/_as_gen/matplotlib.quiver.Quiver.html

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API