matplotlib.quiver.Barbs
-
class matplotlib.quiver.Barbs(ax, *args, pivot='tip', length=7, barbcolor=None, flagcolor=None, sizes=None, fill_empty=False, barb_increments=None, rounding=True, flip_barb=False, **kw)[source] -
Bases:
matplotlib.collections.PolyCollectionСпециализированный PolyCollection для штрихов.
Единственный API-метод —
set_UVC(), который можно использовать для изменения размера, ориентации и цвета стрелок. Позиции изменяются с помощью метода коллекцииset_offsets(). Возможно, этот метод будет полезен в анимациях.Существует одна внутренняя функция
_find_tails(), которая определяет, что должно быть нарисовано на штрихе, исходя из величины вектора. Далее используется_make_barbs(), чтобы определить вершины многоугольника, представляющего штрих, на основе этой информации.Построение 2D поля штрихов.
Вызов:
barbs([X, Y], U, V, [C], **kw)
Где X, Y определяют расположение штрихов, U, V определяют направления штрихов, а C необязательно задаёт цвет.
Все аргументы могут быть одномерными или двумерными. U, V, C могут быть масками, но в настоящее время не поддерживаются маскированные X, Y.
Штрихи традиционно используются в метеорологии для отображения скорости и направления ветра, но технически могут использоваться для отображения любых двухмерных векторных величин. В отличие от стрелок, которые передают величину вектора длиной стрелки, штрихи дают более количественную информацию о величине вектора, рисуя наклонные линии или треугольники для различных приращений величины, как показано схематично ниже:
: /\ \ : / \ \ : / \ \ \ : / \ \ \ : ------------------------------
Наибольшее приращение задаётся треугольником (или «флагом»). После них следуют полные линии (штрихи). Наименьшее приращение — это половина линии. Естественно, может быть не более одной половины линии. Если величина мала и требует только одной половины линии и нет полных линий или треугольников, половина линии смещена от конца штриха, чтобы её легко можно было отличить от штрихов с одной полной линией. Величина для показанного выше штриха в норме равна 65, используя стандартные приращения 50, 10 и 5.
См. также https://en.wikipedia.org/wiki/Wind_barb.
Параметры: -
X, Y1D or 2D array-like, optional -
Координаты x и y расположения штрихов. См. pivot, как штрихи рисуются относительно 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 ствола штриха.
-
C1D or 2D array-like, optional -
Числовые данные, определяющие цвета штрихов с помощью цветовой схемы norm и cmap.
Не поддерживает явные цвета. Если вы хотите установить цвета напрямую, используйте barbcolor вместо этого.
-
lengthfloat, default: 7 -
Длина штриха в пунктах; другие части штриха масштабируются относительно этого.
-
pivot{'tip', 'middle'} or float, default: 'tip' -
Часть стрелки, закреплённой на сетке X, Y. Штрих вращается вокруг этой точки. Это также может быть число, которое смещает начало штриха на указанное количество пунктов от точки сетки.
-
barbcolorcolor or color sequence -
Устанавливает цвет всех частей штриха, кроме флагов. Этот параметр аналогичен параметру edgecolor для многоугольников, который можно использовать вместо этого. Однако этот параметр переопределит facecolor.
-
flagcolorcolor or color sequence -
Устанавливает цвет любых флагов на штрихе. Этот параметр аналогичен параметру facecolor для многоугольников, который можно использовать вместо этого. Однако этот параметр переопределит facecolor. Если он не установлен (и C тоже), то flagcolor будет установлен в соответствии с barbcolor, чтобы штрих имел однородный цвет. Если C установлен, flagcolor не имеет эффекта.
-
sizesdict, optional -
Словарь коэффициентов, определяющих отношение данного элемента к длине штриха. В него должны быть включены только те значения, которые нужно переопределить. Эти элементы включают:
- 'spacing' - расстояние между элементами (флагами, полными/половинными штрихами)
- 'height' - высота (расстояние от ствола до верха) флага или полного штриха
- 'width' - ширина флага, вдвое больше ширины полного штриха
- 'emptybarb' - радиус круга, используемого для малых величин
-
fill_emptybool, default: False -
Заполнять ли пустые штрихи (круги), нарисованные цветом флага. Если они не заполнены, центр прозрачный.
-
roundingbool, default: True -
Округлять ли величину вектора при назначении компонентов штриха. Если True, величина округляется до ближайшего кратного приращению половины штриха. Если False, величина просто обрезается до ближайшего меньшего кратного.
-
barb_incrementsdict, optional -
Словарь приращений, определяющий значения, которые нужно связать с различными частями штриха. В него должны быть включены только те значения, которые нужно переопределить.
- 'half' - половины штрихов (по умолчанию 5)
- 'full' - полные штрихи (по умолчанию 10)
- 'flag' - флаги (по умолчанию 50)
-
flip_barbbool or array-like of bool, default: False -
Обращать ли линии и флаги, противоположные обычному. Нормальное поведение — это то, что штрихи и линии указывают вправо (происходит от штрихов ветра, которые имеют эти элементы, указывающие на низкое давление в Северном полушарии).
Одно значение применяется ко всем штрихам. Отдельные штрихи можно перевернуть, передав массив bool того же размера, что и U и V.
Возвращает: -
barbsBarbs
-
Другие параметры: - **kwargs
-
Стрелки-баробы можно дополнительно настроить, используя ключевые аргументы
PolyCollection:Свойство Описание agg_filterфункция фильтра, которая принимает массив чисел с плавающей запятой (m, n, 3) и значение dpi, и возвращает массив чисел с плавающей запятой (m, n, 3) alphaчисло или None animatedбулево значение antialiasedили aa или antialiasedsбулево значение или последовательность булевых значений arrayмассив NumPy capstyle{'butt', 'round', 'projecting'} clim(vmin: float, vmax: float) clip_boxBboxclip_onбулево значение clip_pathОбъект Patch или (объект Path, трансформация) или None cmapколористическая карта или зарегистрированное имя колористической карты colorцвет или последовательность кортежей rgba containsвызываемый объект edgecolorили ec или edgecolorsцвет или последовательность цветов или 'face' facecolorили facecolors или fcцвет или последовательность цветов figureFiguregidстрока hatch{'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'} in_layoutбулево значение joinstyle{'miter', 'round', 'bevel'} labelобъект linestyleили dashes или linestyles или ls{'-', '--', '-.', ':', '', (смещение, последовательность вкл/выкл), ...} linewidthили linewidths или lwчисло с плавающей запятой или последовательность чисел с плавающей запятой normNormalizeoffset_position{'screen', 'data'} offsetsпоследовательность (N, 2) или (2,) path_effectsAbstractPathEffectpickerNone или булево значение или число с плавающей запятой или вызываемый объект pickradiusнеизвестно rasterizedбулево значение или None sketch_params(scale: float, length: float, randomness: float) snapбулево значение или None transformTransformurlстрока urlsСписок строк или None visibleбулево значение zorderчисло с плавающей запятой
-
barbs_doc = '\nPlot a 2D field of barbs.\n\nCall signature::\n\n barbs([X, Y], U, V, [C], **kw)\n\nWhere *X*, *Y* define the barb locations, *U*, *V* define the barb\ndirections, and *C* optionally sets the color.\n\nAll arguments may be 1D or 2D. *U*, *V*, *C* may be masked arrays, but masked\n*X*, *Y* are not supported at present.\n\nBarbs are traditionally used in meteorology as a way to plot the speed\nand direction of wind observations, but can technically be used to\nplot any two dimensional vector quantity. As opposed to arrows, which\ngive vector magnitude by the length of the arrow, the barbs give more\nquantitative information about the vector magnitude by putting slanted\nlines or a triangle for various increments in magnitude, as show\nschematically below::\n\n : /\\ \\\n : / \\ \\\n : / \\ \\ \\\n : / \\ \\ \\\n : ------------------------------\n\n\nThe largest increment is given by a triangle (or "flag"). After those\ncome full lines (barbs). The smallest increment is a half line. There\nis only, of course, ever at most 1 half line. If the magnitude is\nsmall and only needs a single half-line and no full lines or\ntriangles, the half-line is offset from the end of the barb so that it\ncan be easily distinguished from barbs with a single full line. The\nmagnitude for the barb shown above would nominally be 65, using the\nstandard increments of 50, 10, and 5.\n\nSee also https://en.wikipedia.org/wiki/Wind_barb.\n\n\n\nParameters\n----------\nX, Y : 1D or 2D array-like, optional\n The x and y coordinates of the barb locations. See *pivot* for how the\n barbs are drawn to the x, y positions.\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 components of the barb shaft.\n\nC : 1D or 2D array-like, optional\n Numeric data that defines the barb 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 *barbcolor* instead.\n\nlength : float, default: 7\n Length of the barb in points; the other parts of the barb\n are scaled against this.\n\npivot : {\'tip\', \'middle\'} or float, default: \'tip\'\n The part of the arrow that is anchored to the *X*, *Y* grid. The barb\n rotates about this point. This can also be a number, which shifts the\n start of the barb that many points away from grid point.\n\nbarbcolor : color or color sequence\n Specifies the color of all parts of the barb except for the flags. This\n parameter is analogous to the *edgecolor* parameter for polygons,\n which can be used instead. However this parameter will override\n facecolor.\n\nflagcolor : color or color sequence\n Specifies the color of any flags on the barb. This parameter is\n analogous to the *facecolor* parameter for polygons, which can be\n used instead. However, this parameter will override facecolor. If\n this is not set (and *C* has not either) then *flagcolor* will be\n set to match *barbcolor* so that the barb has a uniform color. If\n *C* has been set, *flagcolor* has no effect.\n\nsizes : dict, optional\n A dictionary of coefficients specifying the ratio of a given\n feature to the length of the barb. Only those values one wishes to\n override need to be included. These features include:\n\n - \'spacing\' - space between features (flags, full/half barbs)\n - \'height\' - height (distance from shaft to top) of a flag or full barb\n - \'width\' - width of a flag, twice the width of a full barb\n - \'emptybarb\' - radius of the circle used for low magnitudes\n\nfill_empty : bool, default: False\n Whether the empty barbs (circles) that are drawn should be filled with\n the flag color. If they are not filled, the center is transparent.\n\nrounding : bool, default: True\n Whether the vector magnitude should be rounded when allocating barb\n components. If True, the magnitude is rounded to the nearest multiple\n of the half-barb increment. If False, the magnitude is simply truncated\n to the next lowest multiple.\n\nbarb_increments : dict, optional\n A dictionary of increments specifying values to associate with\n different parts of the barb. Only those values one wishes to\n override need to be included.\n\n - \'half\' - half barbs (Default is 5)\n - \'full\' - full barbs (Default is 10)\n - \'flag\' - flags (default is 50)\n\nflip_barb : bool or array-like of bool, default: False\n Whether the lines and flags should point opposite to normal.\n Normal behavior is for the barbs and lines to point right (comes from wind\n barbs having these features point towards low pressure in the Northern\n Hemisphere).\n\n A single value is applied to all barbs. Individual barbs can be flipped by\n passing a bool array of the same size as *U* and *V*.\n\nReturns\n-------\nbarbs : `~matplotlib.quiver.Barbs`\n\nOther Parameters\n----------------\n**kwargs\n The barbs can further be customized using `.PolyCollection` keyword\n arguments:\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'
-
set_UVC(self, U, V, C=None)[source]
-
set_offsets(self, xy)[source] -
Устанавливает смещения для многоугольников стрелок-бароб. Сохраняет переданные смещения и применяет маскирование, соответствующее имеющимся данным U/V.
Параметры: -
xysequence of pairs of floats
-
© 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.Barbs.html