Python matplotlib plot marker

matplotlib.pyplot.plot#

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.

>>> plot(x, y) # plot x and y using default line style and color >>> plot(x, y, 'bo') # plot x and y using blue circle markers >>> plot(y) # plot y using x as index array 0..N-1 >>> plot(y, 'r+') # ditto, but with red plusses 

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:

>>> plot(x, y, 'go--', linewidth=2, markersize=12) >>> plot(x, y, color='green', marker='o', linestyle='dashed', . linewidth=2, markersize=12) 

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:

>>> plot('xlabel', 'ylabel', data=obj) 

All indexable objects are supported. This could e.g. be a dict , a pandas.DataFrame or a structured numpy array.

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:

>>> plot(x1, y1, 'bo') >>> plot(x2, y2, 'go') 
>>> x = [1, 2, 3] >>> y = np.array([[1, 2], [3, 4], [5, 6]]) >>> plot(x, y) 
>>> for col in range(y.shape[1]): . plot(x, y[:, col]) 

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’]) ).

Parameters : x, y array-like or scalar

The horizontal / vertical coordinates of the data points. x values are optional and default to range(len(y)) .

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.

Technically there’s a slight ambiguity in calls where the second label is a valid fmt. plot(‘n’, ‘o’, data=obj) could be plt(x, y) or plt(y, fmt) . In such cases, the former interpretation is chosen, but a warning is issued. You may suppress the warning by adding an empty format string plot(‘n’, ‘o’, », data=obj) .

A list of lines representing the plotted data.

Other Parameters : scalex, scaley bool, default: True

These parameters determine if the view limits are adapted to the data limits. The values are passed on to autoscale_view .

**kwargs Line2D properties, optional

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

>>> plot([1, 2, 3], [1, 2, 3], 'go-', label='line 1', linewidth=2) >>> plot([1, 2, 3], [1, 4, 9], 'rs', label='line 2') 

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:

a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image

Источник

matplotlib.markers #

Functions to handle markers; used by the marker functionality of plot , scatter , and errorbar .

All possible markers are defined here:

m00

m01

m02

m03

m04

m05

m06

m07

m08

m09

m10

m11

m12

m13

m23

m14

m15

m16

m17

m18

m24

m19

m20

m21

m22

m25

m26

m27

m28

m29

m30

m31

m32

m33

caretleft (centered at base)

m34

caretright (centered at base)

m35

m36

caretdown (centered at base)

m37

Render the string using mathtext. E.g «$f$» for marker showing the letter f .

A list of (x, y) pairs used for Path vertices. The center of the marker is located at (0, 0) and the size is normalized, such that the created path is encapsulated inside the unit cell.

A regular polygon with numsides sides, rotated by angle .

A star-like symbol with numsides sides, rotated by angle .

An asterisk with numsides sides, rotated by angle .

As a deprecated feature, None also means ‘nothing’ when directly constructing a MarkerStyle , but note that there are other contexts where marker=None instead means «the default marker» (e.g. rcParams[«scatter.marker»] (default: ‘o’ ) for Axes.scatter ).

Note that special symbols can be defined via the STIX math font , e.g. «$\u266B$» . For an overview over the STIX font symbols refer to the STIX font table. Also see the STIX Fonts .

Integer numbers from 0 to 11 create lines and triangles. Those are equally accessible via capitalized variables, like CARETDOWNBASE . Hence the following are equivalent:

plt.plot([1, 2, 3], marker=11) plt.plot([1, 2, 3], marker=matplotlib.markers.CARETDOWNBASE) 

Markers join and cap styles can be customized by creating a new instance of MarkerStyle. A MarkerStyle can also have a custom Transform allowing it to be arbitrarily rotated or offset.

Examples showing the use of markers:

Classes#

A class representing marker types.

Источник

Marker reference#

Matplotlib supports multiple categories of markers which are selected using the marker parameter of plot commands:

For a list of all markers see also the matplotlib.markers documentation.

from matplotlib.markers import MarkerStyle import matplotlib.pyplot as plt from matplotlib.lines import Line2D from matplotlib.transforms import Affine2D text_style = dict(horizontalalignment='right', verticalalignment='center', fontsize=12, fontfamily='monospace') marker_style = dict(linestyle=':', color='0.8', markersize=10, markerfacecolor="tab:blue", markeredgecolor="tab:blue") def format_axes(ax): ax.margins(0.2) ax.set_axis_off() ax.invert_yaxis() def split_list(a_list): i_half = len(a_list) // 2 return a_list[:i_half], a_list[i_half:] 

Unfilled markers#

Unfilled markers are single-colored.

fig, axs = plt.subplots(ncols=2) fig.suptitle('Un-filled markers', fontsize=14) # Filter out filled markers and marker settings that do nothing. unfilled_markers = [m for m, func in Line2D.markers.items() if func != 'nothing' and m not in Line2D.filled_markers] for ax, markers in zip(axs, split_list(unfilled_markers)): for y, marker in enumerate(markers): ax.text(-0.5, y, repr(marker), **text_style) ax.plot([y] * 3, marker=marker, **marker_style) format_axes(ax) 

Un-filled markers

Filled markers#

fig, axs = plt.subplots(ncols=2) fig.suptitle('Filled markers', fontsize=14) for ax, markers in zip(axs, split_list(Line2D.filled_markers)): for y, marker in enumerate(markers): ax.text(-0.5, y, repr(marker), **text_style) ax.plot([y] * 3, marker=marker, **marker_style) format_axes(ax) 

Filled markers

Marker fill styles#

The edge color and fill color of filled markers can be specified separately. Additionally, the fillstyle can be configured to be unfilled, fully filled, or half-filled in various directions. The half-filled styles use markerfacecoloralt as secondary fill color.

fig, ax = plt.subplots() fig.suptitle('Marker fillstyle', fontsize=14) fig.subplots_adjust(left=0.4) filled_marker_style = dict(marker='o', linestyle=':', markersize=15, color='darkgrey', markerfacecolor='tab:blue', markerfacecoloralt='lightsteelblue', markeredgecolor='brown') for y, fill_style in enumerate(Line2D.fillStyles): ax.text(-0.5, y, repr(fill_style), **text_style) ax.plot([y] * 3, fillstyle=fill_style, **filled_marker_style) format_axes(ax) 

Marker fillstyle

Markers created from TeX symbols#

Use MathText , to use custom marker symbols, like e.g. «$\u266B$» . For an overview over the STIX font symbols refer to the STIX font table. Also see the STIX Fonts .

fig, ax = plt.subplots() fig.suptitle('Mathtext markers', fontsize=14) fig.subplots_adjust(left=0.4) marker_style.update(markeredgecolor="none", markersize=15) markers = ["$1$", r"$\frac $", "$f$", "$\u266B$", r"$\mathcal $"] for y, marker in enumerate(markers): # Escape dollars so that the text is written "as is", not as mathtext. ax.text(-0.5, y, repr(marker).replace("$", r"\$"), **text_style) ax.plot([y] * 3, marker=marker, **marker_style) format_axes(ax) 

Mathtext markers

Markers created from Paths#

Any Path can be used as a marker. The following example shows two simple paths star and circle, and a more elaborate path of a circle with a cut-out star.

import matplotlib.path as mpath import numpy as np star = mpath.Path.unit_regular_star(6) circle = mpath.Path.unit_circle() # concatenate the circle with an internal cutout of the star cut_star = mpath.Path( vertices=np.concatenate([circle.vertices, star.vertices[::-1, . ]]), codes=np.concatenate([circle.codes, star.codes])) fig, ax = plt.subplots() fig.suptitle('Path markers', fontsize=14) fig.subplots_adjust(left=0.4) markers = 'star': star, 'circle': circle, 'cut_star': cut_star> for y, (name, marker) in enumerate(markers.items()): ax.text(-0.5, y, name, **text_style) ax.plot([y] * 3, marker=marker, **marker_style) format_axes(ax) 

Path markers

Advanced marker modifications with transform#

Markers can be modified by passing a transform to the MarkerStyle constructor. Following example shows how a supplied rotation is applied to several marker shapes.

common_style = k: v for k, v in filled_marker_style.items() if k != 'marker'> angles = [0, 10, 20, 30, 45, 60, 90] fig, ax = plt.subplots() fig.suptitle('Rotated markers', fontsize=14) ax.text(-0.5, 0, 'Filled marker', **text_style) for x, theta in enumerate(angles): t = Affine2D().rotate_deg(theta) ax.plot(x, 0, marker=MarkerStyle('o', 'left', t), **common_style) ax.text(-0.5, 1, 'Un-filled marker', **text_style) for x, theta in enumerate(angles): t = Affine2D().rotate_deg(theta) ax.plot(x, 1, marker=MarkerStyle('1', 'left', t), **common_style) ax.text(-0.5, 2, 'Equation marker', **text_style) for x, theta in enumerate(angles): t = Affine2D().rotate_deg(theta) eq = r'$\frac $' ax.plot(x, 2, marker=MarkerStyle(eq, 'left', t), **common_style) for x, theta in enumerate(angles): ax.text(x, 2.5, f"theta>°", horizontalalignment="center") format_axes(ax) fig.tight_layout() 

Rotated markers

Setting marker cap style and join style#

Markers have default cap and join styles, but these can be customized when creating a MarkerStyle.

from matplotlib.markers import JoinStyle, CapStyle marker_inner = dict(markersize=35, markerfacecolor='tab:blue', markerfacecoloralt='lightsteelblue', markeredgecolor='brown', markeredgewidth=8, ) marker_outer = dict(markersize=35, markerfacecolor='tab:blue', markerfacecoloralt='lightsteelblue', markeredgecolor='white', markeredgewidth=1, ) fig, ax = plt.subplots() fig.suptitle('Marker CapStyle', fontsize=14) fig.subplots_adjust(left=0.1) for y, cap_style in enumerate(CapStyle): ax.text(-0.5, y, cap_style.name, **text_style) for x, theta in enumerate(angles): t = Affine2D().rotate_deg(theta) m = MarkerStyle('1', transform=t, capstyle=cap_style) ax.plot(x, y, marker=m, **marker_inner) ax.plot(x, y, marker=m, **marker_outer) ax.text(x, len(CapStyle) - .5, f'theta>°', ha='center') format_axes(ax) 

Marker CapStyle

fig, ax = plt.subplots() fig.suptitle('Marker JoinStyle', fontsize=14) fig.subplots_adjust(left=0.05) for y, join_style in enumerate(JoinStyle): ax.text(-0.5, y, join_style.name, **text_style) for x, theta in enumerate(angles): t = Affine2D().rotate_deg(theta) m = MarkerStyle('*', transform=t, joinstyle=join_style) ax.plot(x, y, marker=m, **marker_inner) ax.text(x, len(JoinStyle) - .5, f'theta>°', ha='center') format_axes(ax) plt.show() 

Marker JoinStyle

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

Источник

Читайте также:  Html upload text files
Оцените статью