image
imagewidth (px)
75
2.22k
code
stringlengths
300
16.2k
example_id
stringlengths
28
79
figure_index
int64
0
26
figure_name
stringclasses
28 values
title
stringlengths
38
94
example_page_url
stringlengths
61
195
source_url
stringlengths
80
111
source_relpath
stringlengths
6
37
category_hint
stringclasses
24 values
status
stringclasses
1 value
num_figures
int64
1
27
error
null
""" ========================= Date precision and epochs ========================= Matplotlib can handle `.datetime` objects and `numpy.datetime64` objects using a unit converter that recognizes these dates and converts them to floating point numbers. Before Matplotlib 3.3, the default for this conversion returns a float that was days since "0000-12-31T00:00:00". As of Matplotlib 3.3, the default is days from "1970-01-01T00:00:00". This allows more resolution for modern dates. "2020-01-01" with the old epoch converted to 730120, and a 64-bit floating point number has a resolution of 2^{-52}, or approximately 14 microseconds, so microsecond precision was lost. With the new default epoch "2020-01-01" is 10957.0, so the achievable resolution is 0.21 microseconds. """ import datetime import matplotlib.pyplot as plt import numpy as np import matplotlib.dates as mdates def _reset_epoch_for_tutorial(): """ Users (and downstream libraries) should not use the private method of resetting the epoch. """ mdates._reset_epoch_test_example() # %% # Datetime # -------- # # Python `.datetime` objects have microsecond resolution, so with the # old default matplotlib dates could not round-trip full-resolution datetime # objects. old_epoch = '0000-12-31T00:00:00' new_epoch = '1970-01-01T00:00:00' _reset_epoch_for_tutorial() # Don't do this. Just for this tutorial. mdates.set_epoch(old_epoch) # old epoch (pre MPL 3.3) date1 = datetime.datetime(2000, 1, 1, 0, 10, 0, 12, tzinfo=datetime.timezone.utc) mdate1 = mdates.date2num(date1) print('Before Roundtrip: ', date1, 'Matplotlib date:', mdate1) date2 = mdates.num2date(mdate1) print('After Roundtrip: ', date2) # %% # Note this is only a round-off error, and there is no problem for # dates closer to the old epoch: date1 = datetime.datetime(10, 1, 1, 0, 10, 0, 12, tzinfo=datetime.timezone.utc) mdate1 = mdates.date2num(date1) print('Before Roundtrip: ', date1, 'Matplotlib date:', mdate1) date2 = mdates.num2date(mdate1) print('After Roundtrip: ', date2) # %% # If a user wants to use modern dates at microsecond precision, they # can change the epoch using `.set_epoch`. However, the epoch has to be # set before any date operations to prevent confusion between different # epochs. Trying to change the epoch later will raise a `RuntimeError`. try: mdates.set_epoch(new_epoch) # this is the new MPL 3.3 default. except RuntimeError as e: print('RuntimeError:', str(e)) # %% # For this tutorial, we reset the sentinel using a private method, but users # should just set the epoch once, if at all. _reset_epoch_for_tutorial() # Just being done for this tutorial. mdates.set_epoch(new_epoch) date1 = datetime.datetime(2020, 1, 1, 0, 10, 0, 12, tzinfo=datetime.timezone.utc) mdate1 = mdates.date2num(date1) print('Before Roundtrip: ', date1, 'Matplotlib date:', mdate1) date2 = mdates.num2date(mdate1) print('After Roundtrip: ', date2) # %% # datetime64 # ---------- # # `numpy.datetime64` objects have microsecond precision for a much larger # timespace than `.datetime` objects. However, currently Matplotlib time is # only converted back to datetime objects, which have microsecond resolution, # and years that only span 0000 to 9999. _reset_epoch_for_tutorial() # Don't do this. Just for this tutorial. mdates.set_epoch(new_epoch) date1 = np.datetime64('2000-01-01T00:10:00.000012') mdate1 = mdates.date2num(date1) print('Before Roundtrip: ', date1, 'Matplotlib date:', mdate1) date2 = mdates.num2date(mdate1) print('After Roundtrip: ', date2) # %% # Plotting # -------- # # This all of course has an effect on plotting. With the old default epoch # the times were rounded during the internal ``date2num`` conversion, leading # to jumps in the data: _reset_epoch_for_tutorial() # Don't do this. Just for this tutorial. mdates.set_epoch(old_epoch) x = np.arange('2000-01-01T00:00:00.0', '2000-01-01T00:00:00.000100', dtype='datetime64[us]') # simulate the plot being made using the old epoch xold = np.array([mdates.num2date(mdates.date2num(d)) for d in x]) y = np.arange(0, len(x)) # resetting the Epoch so plots are comparable _reset_epoch_for_tutorial() # Don't do this. Just for this tutorial. mdates.set_epoch(new_epoch) fig, ax = plt.subplots(layout='constrained') ax.plot(xold, y) ax.set_title('Epoch: ' + mdates.get_epoch()) ax.xaxis.set_tick_params(rotation=40) plt.show() # %% # For dates plotted using the more recent epoch, the plot is smooth: fig, ax = plt.subplots(layout='constrained') ax.plot(x, y) ax.set_title('Epoch: ' + mdates.get_epoch()) ax.xaxis.set_tick_params(rotation=40) plt.show() _reset_epoch_for_tutorial() # Don't do this. Just for this tutorial. # %% # # .. admonition:: References # # The use of the following functions, methods, classes and modules is shown # in this example: # # - `matplotlib.dates.num2date` # - `matplotlib.dates.date2num` # - `matplotlib.dates.set_epoch`
stable__gallery__ticks__date_precision_and_epochs
0
figure_000.png
Date precision and epochs — Matplotlib 3.10.8 documentation
https://matplotlib.org/stable/gallery/ticks/date_precision_and_epochs.html#sphx-glr-download-gallery-ticks-date-precision-and-epochs-py
https://matplotlib.org/stable/_downloads/586a88c62e8a2d883ea392b25f0e62a9/date_precision_and_epochs.py
date_precision_and_epochs.py
ticks
ok
2
null
""" ============ Dollar ticks ============ Use a format string to prepend dollar signs on y-axis labels. .. redirect-from:: /gallery/pyplots/dollar_ticks """ import matplotlib.pyplot as plt import numpy as np # Fixing random state for reproducibility np.random.seed(19680801) fig, ax = plt.subplots() ax.plot(100*np.random.rand(20)) # Use automatic StrMethodFormatter ax.yaxis.set_major_formatter('${x:1.2f}') ax.yaxis.set_tick_params(which='major', labelcolor='green', labelleft=False, labelright=True) plt.show() # %% # # .. admonition:: References # # The use of the following functions, methods, classes and modules is shown # in this example: # # - `matplotlib.pyplot.subplots` # - `matplotlib.axis.Axis.set_major_formatter` # - `matplotlib.axis.Axis.set_tick_params` # - `matplotlib.axis.Tick` # - `matplotlib.ticker.StrMethodFormatter`
stable__gallery__ticks__dollar_ticks
0
figure_000.png
Dollar ticks — Matplotlib 3.10.8 documentation
https://matplotlib.org/stable/gallery/ticks/dollar_ticks.html#sphx-glr-download-gallery-ticks-dollar-ticks-py
https://matplotlib.org/stable/_downloads/c42c8ac5c413d3d2897f606da8b90ccd/dollar_ticks.py
dollar_ticks.py
ticks
ok
1
null
""" =================================================== SI prefixed offsets and natural order of magnitudes =================================================== `matplotlib.ticker.EngFormatter` is capable of computing a natural offset for your axis data, and presenting it with a standard SI prefix automatically calculated. Below is an examples of such a plot: """ import matplotlib.pyplot as plt import numpy as np import matplotlib.ticker as mticker # Fixing random state for reproducibility np.random.seed(19680801) UNIT = "Hz" fig, ax = plt.subplots() ax.yaxis.set_major_formatter(mticker.EngFormatter( useOffset=True, unit=UNIT )) size = 100 measurement = np.full(size, 1e9) noise = np.random.uniform(low=-2e3, high=2e3, size=size) ax.plot(measurement + noise) plt.show()
stable__gallery__ticks__engformatter_offset
0
figure_000.png
SI prefixed offsets and natural order of magnitudes — Matplotlib 3.10.8 documentation
https://matplotlib.org/stable/gallery/ticks/engformatter_offset.html#sphx-glr-download-gallery-ticks-engformatter-offset-py
https://matplotlib.org/stable/_downloads/0626606af53131a40fb15598b3954d64/engformatter_offset.py
engformatter_offset.py
ticks
ok
1
null
""" ========================= Fig Axes Customize Simple ========================= Customize the background, labels and ticks of a simple plot. .. redirect-from:: /gallery/pyplots/fig_axes_customize_simple """ import matplotlib.pyplot as plt # %% # `.pyplot.figure` creates a `matplotlib.figure.Figure` instance. fig = plt.figure() rect = fig.patch # a rectangle instance rect.set_facecolor('lightgoldenrodyellow') ax1 = fig.add_axes([0.1, 0.3, 0.4, 0.4]) rect = ax1.patch rect.set_facecolor('lightslategray') ax1.tick_params(axis='x', labelcolor='tab:red', labelrotation=45, labelsize=16) ax1.tick_params(axis='y', color='tab:green', size=25, width=3) plt.show() # %% # # .. admonition:: References # # The use of the following functions, methods, classes and modules is shown # in this example: # # - `matplotlib.axis.Axis.get_ticklabels` # - `matplotlib.axis.Axis.get_ticklines` # - `matplotlib.text.Text.set_rotation` # - `matplotlib.text.Text.set_fontsize` # - `matplotlib.text.Text.set_color` # - `matplotlib.lines.Line2D` # - `matplotlib.lines.Line2D.set_markeredgecolor` # - `matplotlib.lines.Line2D.set_markersize` # - `matplotlib.lines.Line2D.set_markeredgewidth` # - `matplotlib.patches.Patch.set_facecolor`
stable__gallery__ticks__fig_axes_customize_simple
0
figure_000.png
Fig Axes Customize Simple — Matplotlib 3.10.8 documentation
https://matplotlib.org/stable/gallery/ticks/fig_axes_customize_simple.html#sphx-glr-download-gallery-ticks-fig-axes-customize-simple-py
https://matplotlib.org/stable/_downloads/c2319cc152ca13b70dc936f2c7792dc2/fig_axes_customize_simple.py
fig_axes_customize_simple.py
ticks
ok
1
null
r""" ===================== Major and minor ticks ===================== Demonstrate how to use major and minor tickers. The two relevant classes are `.Locator`\s and `.Formatter`\s. Locators determine where the ticks are, and formatters control the formatting of tick labels. Minor ticks are off by default (using `.NullLocator` and `.NullFormatter`). Minor ticks can be turned on without labels by setting the minor locator. Minor tick labels can be turned on by setting the minor formatter. `.MultipleLocator` places ticks on multiples of some base. `.StrMethodFormatter` uses a format string (e.g., ``'{x:d}'`` or ``'{x:1.2f}'`` or ``'{x:1.1f} cm'``) to format the tick labels (the variable in the format string must be ``'x'``). For a `.StrMethodFormatter`, the string can be passed directly to `.Axis.set_major_formatter` or `.Axis.set_minor_formatter`. An appropriate `.StrMethodFormatter` will be created and used automatically. `.pyplot.grid` changes the grid settings of the major ticks of the x- and y-axis together. If you want to control the grid of the minor ticks for a given axis, use for example :: ax.xaxis.grid(True, which='minor') Note that a given locator or formatter instance can only be used on a single axis (because the locator stores references to the axis data and view limits). """ import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import AutoMinorLocator, MultipleLocator t = np.arange(0.0, 100.0, 0.1) s = np.sin(0.1 * np.pi * t) * np.exp(-t * 0.01) fig, ax = plt.subplots() ax.plot(t, s) # Make a plot with major ticks that are multiples of 20 and minor ticks that # are multiples of 5. Label major ticks with '.0f' formatting but don't label # minor ticks. The string is used directly, the `StrMethodFormatter` is # created automatically. ax.xaxis.set_major_locator(MultipleLocator(20)) ax.xaxis.set_major_formatter('{x:.0f}') # For the minor ticks, use no labels; default NullFormatter. ax.xaxis.set_minor_locator(MultipleLocator(5)) plt.show() # %% # Automatic tick selection for major and minor ticks. # # Use interactive pan and zoom to see how the tick intervals change. There will # be either 4 or 5 minor tick intervals per major interval, depending on the # major interval. # # One can supply an argument to `.AutoMinorLocator` to specify a fixed number # of minor intervals per major interval, e.g. ``AutoMinorLocator(2)`` would # lead to a single minor tick between major ticks. t = np.arange(0.0, 100.0, 0.01) s = np.sin(2 * np.pi * t) * np.exp(-t * 0.01) fig, ax = plt.subplots() ax.plot(t, s) ax.xaxis.set_minor_locator(AutoMinorLocator()) ax.tick_params(which='both', width=2) ax.tick_params(which='major', length=7) ax.tick_params(which='minor', length=4, color='r') plt.show() # %% # # .. admonition:: References # # The use of the following functions, methods, classes and modules is shown # in this example: # # - `matplotlib.pyplot.subplots` # - `matplotlib.axis.Axis.set_major_formatter` # - `matplotlib.axis.Axis.set_major_locator` # - `matplotlib.axis.Axis.set_minor_locator` # - `matplotlib.ticker.AutoMinorLocator` # - `matplotlib.ticker.MultipleLocator` # - `matplotlib.ticker.StrMethodFormatter`
stable__gallery__ticks__major_minor_demo
0
figure_000.png
Major and minor ticks — Matplotlib 3.10.8 documentation
https://matplotlib.org/stable/gallery/ticks/major_minor_demo.html#sphx-glr-download-gallery-ticks-major-minor-demo-py
https://matplotlib.org/stable/_downloads/4ad72df52615cfce120da1981d41d969/major_minor_demo.py
major_minor_demo.py
ticks
ok
2
null
""" ========================= Multilevel (nested) ticks ========================= Sometimes we want another level of tick labels on an axis, perhaps to indicate a grouping of the ticks. Matplotlib does not provide an automated way to do this, but it is relatively straightforward to annotate below the main axis. These examples use `.Axes.secondary_xaxis`, which is one approach. It has the advantage that we can use Matplotlib Locators and Formatters on the axis that does the grouping if we want. This first example creates a secondary xaxis and manually adds the ticks and labels using `.Axes.set_xticks`. Note that the tick labels have a newline (e.g. ``"\nOughts"``) at the beginning of them to put the second-level tick labels below the main tick labels. """ import matplotlib.pyplot as plt import numpy as np import matplotlib.dates as mdates rng = np.random.default_rng(19680801) fig, ax = plt.subplots(layout='constrained', figsize=(4, 4)) ax.plot(np.arange(30)) sec = ax.secondary_xaxis(location=0) sec.set_xticks([5, 15, 25], labels=['\nOughts', '\nTeens', '\nTwenties']) # %% # This second example adds a second level of annotation to a categorical axis. # Here we need to note that each animal (category) is assigned an integer, so # ``cats`` is at x=0, ``dogs`` at x=1 etc. Then we place the ticks on the # second level on an x that is at the middle of the animal class we are trying # to delineate. # # This example also adds tick marks between the classes by adding a second # secondary xaxis, and placing long, wide ticks at the boundaries between the # animal classes. fig, ax = plt.subplots(layout='constrained', figsize=(7, 4)) ax.plot(['cats', 'dogs', 'pigs', 'snakes', 'lizards', 'chickens', 'eagles', 'herons', 'buzzards'], rng.normal(size=9), 'o') # label the classes: sec = ax.secondary_xaxis(location=0) sec.set_xticks([1, 3.5, 6.5], labels=['\n\nMammals', '\n\nReptiles', '\n\nBirds']) sec.tick_params('x', length=0) # lines between the classes: sec2 = ax.secondary_xaxis(location=0) sec2.set_xticks([-0.5, 2.5, 4.5, 8.5], labels=[]) sec2.tick_params('x', length=40, width=1.5) ax.set_xlim(-0.6, 8.6) # %% # Dates are another common place where we may want to have a second level of # tick labels. In this last example, we take advantage of the ability to add # an automatic locator and formatter to the secondary xaxis, which means we do # not need to set the ticks manually. # # This example also differs from the above, in that we placed it at a location # below the main axes ``location=-0.075`` and then we hide the spine by setting # the line width to zero. That means that our formatter no longer needs the # carriage returns of the previous two examples. fig, ax = plt.subplots(layout='constrained', figsize=(7, 4)) time = np.arange(np.datetime64('2020-01-01'), np.datetime64('2020-03-31'), np.timedelta64(1, 'D')) ax.plot(time, rng.random(size=len(time))) # just format the days: ax.xaxis.set_major_formatter(mdates.DateFormatter('%d')) # label the months: sec = ax.secondary_xaxis(location=-0.075) sec.xaxis.set_major_locator(mdates.MonthLocator(bymonthday=1)) # note the extra spaces in the label to align the month label inside the month. # Note that this could have been done by changing ``bymonthday`` above as well: sec.xaxis.set_major_formatter(mdates.DateFormatter(' %b')) sec.tick_params('x', length=0) sec.spines['bottom'].set_linewidth(0) # label the xaxis, but note for this to look good, it needs to be on the # secondary xaxis. sec.set_xlabel('Dates (2020)') plt.show()
stable__gallery__ticks__multilevel_ticks
0
figure_000.png
Multilevel (nested) ticks — Matplotlib 3.10.8 documentation
https://matplotlib.org/stable/gallery/ticks/multilevel_ticks.html#sphx-glr-download-gallery-ticks-multilevel-ticks-py
https://matplotlib.org/stable/_downloads/3525cc5d1774b69b18d51894d36a5368/multilevel_ticks.py
multilevel_ticks.py
ticks
ok
3
null
""" ========================= Multilevel (nested) ticks ========================= Sometimes we want another level of tick labels on an axis, perhaps to indicate a grouping of the ticks. Matplotlib does not provide an automated way to do this, but it is relatively straightforward to annotate below the main axis. These examples use `.Axes.secondary_xaxis`, which is one approach. It has the advantage that we can use Matplotlib Locators and Formatters on the axis that does the grouping if we want. This first example creates a secondary xaxis and manually adds the ticks and labels using `.Axes.set_xticks`. Note that the tick labels have a newline (e.g. ``"\nOughts"``) at the beginning of them to put the second-level tick labels below the main tick labels. """ import matplotlib.pyplot as plt import numpy as np import matplotlib.dates as mdates rng = np.random.default_rng(19680801) fig, ax = plt.subplots(layout='constrained', figsize=(4, 4)) ax.plot(np.arange(30)) sec = ax.secondary_xaxis(location=0) sec.set_xticks([5, 15, 25], labels=['\nOughts', '\nTeens', '\nTwenties']) # %% # This second example adds a second level of annotation to a categorical axis. # Here we need to note that each animal (category) is assigned an integer, so # ``cats`` is at x=0, ``dogs`` at x=1 etc. Then we place the ticks on the # second level on an x that is at the middle of the animal class we are trying # to delineate. # # This example also adds tick marks between the classes by adding a second # secondary xaxis, and placing long, wide ticks at the boundaries between the # animal classes. fig, ax = plt.subplots(layout='constrained', figsize=(7, 4)) ax.plot(['cats', 'dogs', 'pigs', 'snakes', 'lizards', 'chickens', 'eagles', 'herons', 'buzzards'], rng.normal(size=9), 'o') # label the classes: sec = ax.secondary_xaxis(location=0) sec.set_xticks([1, 3.5, 6.5], labels=['\n\nMammals', '\n\nReptiles', '\n\nBirds']) sec.tick_params('x', length=0) # lines between the classes: sec2 = ax.secondary_xaxis(location=0) sec2.set_xticks([-0.5, 2.5, 4.5, 8.5], labels=[]) sec2.tick_params('x', length=40, width=1.5) ax.set_xlim(-0.6, 8.6) # %% # Dates are another common place where we may want to have a second level of # tick labels. In this last example, we take advantage of the ability to add # an automatic locator and formatter to the secondary xaxis, which means we do # not need to set the ticks manually. # # This example also differs from the above, in that we placed it at a location # below the main axes ``location=-0.075`` and then we hide the spine by setting # the line width to zero. That means that our formatter no longer needs the # carriage returns of the previous two examples. fig, ax = plt.subplots(layout='constrained', figsize=(7, 4)) time = np.arange(np.datetime64('2020-01-01'), np.datetime64('2020-03-31'), np.timedelta64(1, 'D')) ax.plot(time, rng.random(size=len(time))) # just format the days: ax.xaxis.set_major_formatter(mdates.DateFormatter('%d')) # label the months: sec = ax.secondary_xaxis(location=-0.075) sec.xaxis.set_major_locator(mdates.MonthLocator(bymonthday=1)) # note the extra spaces in the label to align the month label inside the month. # Note that this could have been done by changing ``bymonthday`` above as well: sec.xaxis.set_major_formatter(mdates.DateFormatter(' %b')) sec.tick_params('x', length=0) sec.spines['bottom'].set_linewidth(0) # label the xaxis, but note for this to look good, it needs to be on the # secondary xaxis. sec.set_xlabel('Dates (2020)') plt.show()
stable__gallery__ticks__multilevel_ticks
1
figure_001.png
Multilevel (nested) ticks — Matplotlib 3.10.8 documentation
https://matplotlib.org/stable/gallery/ticks/multilevel_ticks.html#sphx-glr-download-gallery-ticks-multilevel-ticks-py
https://matplotlib.org/stable/_downloads/3525cc5d1774b69b18d51894d36a5368/multilevel_ticks.py
multilevel_ticks.py
ticks
ok
3
null
""" ========================= Multilevel (nested) ticks ========================= Sometimes we want another level of tick labels on an axis, perhaps to indicate a grouping of the ticks. Matplotlib does not provide an automated way to do this, but it is relatively straightforward to annotate below the main axis. These examples use `.Axes.secondary_xaxis`, which is one approach. It has the advantage that we can use Matplotlib Locators and Formatters on the axis that does the grouping if we want. This first example creates a secondary xaxis and manually adds the ticks and labels using `.Axes.set_xticks`. Note that the tick labels have a newline (e.g. ``"\nOughts"``) at the beginning of them to put the second-level tick labels below the main tick labels. """ import matplotlib.pyplot as plt import numpy as np import matplotlib.dates as mdates rng = np.random.default_rng(19680801) fig, ax = plt.subplots(layout='constrained', figsize=(4, 4)) ax.plot(np.arange(30)) sec = ax.secondary_xaxis(location=0) sec.set_xticks([5, 15, 25], labels=['\nOughts', '\nTeens', '\nTwenties']) # %% # This second example adds a second level of annotation to a categorical axis. # Here we need to note that each animal (category) is assigned an integer, so # ``cats`` is at x=0, ``dogs`` at x=1 etc. Then we place the ticks on the # second level on an x that is at the middle of the animal class we are trying # to delineate. # # This example also adds tick marks between the classes by adding a second # secondary xaxis, and placing long, wide ticks at the boundaries between the # animal classes. fig, ax = plt.subplots(layout='constrained', figsize=(7, 4)) ax.plot(['cats', 'dogs', 'pigs', 'snakes', 'lizards', 'chickens', 'eagles', 'herons', 'buzzards'], rng.normal(size=9), 'o') # label the classes: sec = ax.secondary_xaxis(location=0) sec.set_xticks([1, 3.5, 6.5], labels=['\n\nMammals', '\n\nReptiles', '\n\nBirds']) sec.tick_params('x', length=0) # lines between the classes: sec2 = ax.secondary_xaxis(location=0) sec2.set_xticks([-0.5, 2.5, 4.5, 8.5], labels=[]) sec2.tick_params('x', length=40, width=1.5) ax.set_xlim(-0.6, 8.6) # %% # Dates are another common place where we may want to have a second level of # tick labels. In this last example, we take advantage of the ability to add # an automatic locator and formatter to the secondary xaxis, which means we do # not need to set the ticks manually. # # This example also differs from the above, in that we placed it at a location # below the main axes ``location=-0.075`` and then we hide the spine by setting # the line width to zero. That means that our formatter no longer needs the # carriage returns of the previous two examples. fig, ax = plt.subplots(layout='constrained', figsize=(7, 4)) time = np.arange(np.datetime64('2020-01-01'), np.datetime64('2020-03-31'), np.timedelta64(1, 'D')) ax.plot(time, rng.random(size=len(time))) # just format the days: ax.xaxis.set_major_formatter(mdates.DateFormatter('%d')) # label the months: sec = ax.secondary_xaxis(location=-0.075) sec.xaxis.set_major_locator(mdates.MonthLocator(bymonthday=1)) # note the extra spaces in the label to align the month label inside the month. # Note that this could have been done by changing ``bymonthday`` above as well: sec.xaxis.set_major_formatter(mdates.DateFormatter(' %b')) sec.tick_params('x', length=0) sec.spines['bottom'].set_linewidth(0) # label the xaxis, but note for this to look good, it needs to be on the # secondary xaxis. sec.set_xlabel('Dates (2020)') plt.show()
stable__gallery__ticks__multilevel_ticks
2
figure_002.png
Multilevel (nested) ticks — Matplotlib 3.10.8 documentation
https://matplotlib.org/stable/gallery/ticks/multilevel_ticks.html#sphx-glr-download-gallery-ticks-multilevel-ticks-py
https://matplotlib.org/stable/_downloads/3525cc5d1774b69b18d51894d36a5368/multilevel_ticks.py
multilevel_ticks.py
ticks
ok
3
null
""" ========================== The default tick formatter ========================== By default, tick labels are formatted using a `.ScalarFormatter`, which can be configured via `~.axes.Axes.ticklabel_format`. This example illustrates some possible configurations: - Default. - ``useMathText=True``: Fancy formatting of mathematical expressions. - ``useOffset=False``: Do not use offset notation; see `.ScalarFormatter.set_useOffset`. """ import matplotlib.pyplot as plt import numpy as np x = np.arange(0, 1, .01) fig, axs = plt.subplots( 3, 3, figsize=(9, 9), layout="constrained", gridspec_kw={"hspace": 0.1}) for col in axs.T: col[0].plot(x * 1e5 + 1e10, x * 1e-10 + 1e-5) col[1].plot(x * 1e5, x * 1e-4) col[2].plot(-x * 1e5 - 1e10, -x * 1e-5 - 1e-10) for ax in axs[:, 1]: ax.ticklabel_format(useMathText=True) for ax in axs[:, 2]: ax.ticklabel_format(useOffset=False) plt.rcParams.update({"axes.titleweight": "bold", "axes.titley": 1.1}) axs[0, 0].set_title("default settings") axs[0, 1].set_title("useMathText=True") axs[0, 2].set_title("useOffset=False") plt.show()
stable__gallery__ticks__scalarformatter
0
figure_000.png
The default tick formatter — Matplotlib 3.10.8 documentation
https://matplotlib.org/stable/gallery/ticks/scalarformatter.html#the-default-tick-formatter
https://matplotlib.org/stable/_downloads/d09144c4107ab96d8a55006e711872ef/scalarformatter.py
scalarformatter.py
ticks
ok
1
null
""" =============== Tick formatters =============== Tick formatters define how the numeric value associated with a tick on an axis is formatted as a string. This example illustrates the usage and effect of the most common formatters. The tick format is configured via the function `~.Axis.set_major_formatter` or `~.Axis.set_minor_formatter`. It accepts: - a format string, which implicitly creates a `.StrMethodFormatter`. - a function, implicitly creates a `.FuncFormatter`. - an instance of a `.Formatter` subclass. The most common are - `.NullFormatter`: No labels on the ticks. - `.StrMethodFormatter`: Use string `str.format` method. - `.FormatStrFormatter`: Use %-style formatting. - `.FuncFormatter`: Define labels through a function. - `.FixedFormatter`: Set the label strings explicitly. - `.ScalarFormatter`: Default formatter for scalars: auto-pick the format string. - `.PercentFormatter`: Format labels as a percentage. See :ref:`formatters` for a complete list. """ import matplotlib.pyplot as plt from matplotlib import ticker def setup(ax, title): """Set up common parameters for the Axes in the example.""" # only show the bottom spine ax.yaxis.set_major_locator(ticker.NullLocator()) ax.spines[['left', 'right', 'top']].set_visible(False) # define tick positions ax.xaxis.set_major_locator(ticker.MultipleLocator(1.00)) ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.25)) ax.xaxis.set_ticks_position('bottom') ax.tick_params(which='major', width=1.00, length=5) ax.tick_params(which='minor', width=0.75, length=2.5, labelsize=10) ax.set_xlim(0, 5) ax.set_ylim(0, 1) ax.text(0.0, 0.2, title, transform=ax.transAxes, fontsize=14, fontname='Monospace', color='tab:blue') fig = plt.figure(figsize=(8, 8), layout='constrained') fig0, fig1, fig2 = fig.subfigures(3, height_ratios=[1.5, 1.5, 7.5]) fig0.suptitle('String Formatting', fontsize=16, x=0, ha='left') ax0 = fig0.subplots() setup(ax0, title="'{x} km'") ax0.xaxis.set_major_formatter('{x} km') fig1.suptitle('Function Formatting', fontsize=16, x=0, ha='left') ax1 = fig1.subplots() setup(ax1, title="def(x, pos): return str(x-5)") ax1.xaxis.set_major_formatter(lambda x, pos: str(x-5)) fig2.suptitle('Formatter Object Formatting', fontsize=16, x=0, ha='left') axs2 = fig2.subplots(7, 1) setup(axs2[0], title="NullFormatter()") axs2[0].xaxis.set_major_formatter(ticker.NullFormatter()) setup(axs2[1], title="StrMethodFormatter('{x:.3f}')") axs2[1].xaxis.set_major_formatter(ticker.StrMethodFormatter("{x:.3f}")) setup(axs2[2], title="FormatStrFormatter('#%d')") axs2[2].xaxis.set_major_formatter(ticker.FormatStrFormatter("#%d")) def fmt_two_digits(x, pos): return f'[{x:.2f}]' setup(axs2[3], title='FuncFormatter("[{:.2f}]".format)') axs2[3].xaxis.set_major_formatter(ticker.FuncFormatter(fmt_two_digits)) setup(axs2[4], title="FixedFormatter(['A', 'B', 'C', 'D', 'E', 'F'])") # FixedFormatter should only be used together with FixedLocator. # Otherwise, one cannot be sure where the labels will end up. positions = [0, 1, 2, 3, 4, 5] labels = ['A', 'B', 'C', 'D', 'E', 'F'] axs2[4].xaxis.set_major_locator(ticker.FixedLocator(positions)) axs2[4].xaxis.set_major_formatter(ticker.FixedFormatter(labels)) setup(axs2[5], title="ScalarFormatter()") axs2[5].xaxis.set_major_formatter(ticker.ScalarFormatter(useMathText=True)) setup(axs2[6], title="PercentFormatter(xmax=5)") axs2[6].xaxis.set_major_formatter(ticker.PercentFormatter(xmax=5)) plt.show()
stable__gallery__ticks__tick-formatters
0
figure_000.png
Tick formatters — Matplotlib 3.10.8 documentation
https://matplotlib.org/stable/gallery/ticks/tick-formatters.html#tick-formatters
https://matplotlib.org/stable/_downloads/982150f6f72db2a6042ea9a81adacb7e/tick-formatters.py
tick-formatters.py
ticks
ok
1
null
""" ============= Tick locators ============= Tick locators define the position of the ticks. This example illustrates the usage and effect of the most common locators. """ import matplotlib.pyplot as plt import numpy as np import matplotlib.ticker as ticker def setup(ax, title): """Set up common parameters for the Axes in the example.""" # only show the bottom spine ax.yaxis.set_major_locator(ticker.NullLocator()) ax.spines[['left', 'right', 'top']].set_visible(False) ax.xaxis.set_ticks_position('bottom') ax.tick_params(which='major', width=1.00, length=5) ax.tick_params(which='minor', width=0.75, length=2.5) ax.set_xlim(0, 5) ax.set_ylim(0, 1) ax.text(0.0, 0.2, title, transform=ax.transAxes, fontsize=14, fontname='Monospace', color='tab:blue') fig, axs = plt.subplots(8, 1, figsize=(8, 6)) # Null Locator setup(axs[0], title="NullLocator()") axs[0].xaxis.set_major_locator(ticker.NullLocator()) axs[0].xaxis.set_minor_locator(ticker.NullLocator()) # Multiple Locator setup(axs[1], title="MultipleLocator(0.5, offset=0.2)") axs[1].xaxis.set_major_locator(ticker.MultipleLocator(0.5, offset=0.2)) axs[1].xaxis.set_minor_locator(ticker.MultipleLocator(0.1)) # Fixed Locator setup(axs[2], title="FixedLocator([0, 1, 5])") axs[2].xaxis.set_major_locator(ticker.FixedLocator([0, 1, 5])) axs[2].xaxis.set_minor_locator(ticker.FixedLocator(np.linspace(0.2, 0.8, 4))) # Linear Locator setup(axs[3], title="LinearLocator(numticks=3)") axs[3].xaxis.set_major_locator(ticker.LinearLocator(3)) axs[3].xaxis.set_minor_locator(ticker.LinearLocator(31)) # Index Locator setup(axs[4], title="IndexLocator(base=0.5, offset=0.25)") axs[4].plot([0]*5, color='white') axs[4].xaxis.set_major_locator(ticker.IndexLocator(base=0.5, offset=0.25)) # Auto Locator setup(axs[5], title="AutoLocator()") axs[5].xaxis.set_major_locator(ticker.AutoLocator()) axs[5].xaxis.set_minor_locator(ticker.AutoMinorLocator()) # MaxN Locator setup(axs[6], title="MaxNLocator(n=4)") axs[6].xaxis.set_major_locator(ticker.MaxNLocator(4)) axs[6].xaxis.set_minor_locator(ticker.MaxNLocator(40)) # Log Locator setup(axs[7], title="LogLocator(base=10, numticks=15)") axs[7].set_xlim(10**3, 10**10) axs[7].set_xscale('log') axs[7].xaxis.set_major_locator(ticker.LogLocator(base=10, numticks=15)) plt.tight_layout() plt.show() # %% # # .. admonition:: References # # The following functions, methods, classes and modules are used in this example: # # - `matplotlib.axis.Axis.set_major_locator` # - `matplotlib.axis.Axis.set_minor_locator` # - `matplotlib.ticker.NullLocator` # - `matplotlib.ticker.MultipleLocator` # - `matplotlib.ticker.FixedLocator` # - `matplotlib.ticker.LinearLocator` # - `matplotlib.ticker.IndexLocator` # - `matplotlib.ticker.AutoLocator` # - `matplotlib.ticker.MaxNLocator` # - `matplotlib.ticker.LogLocator`
stable__gallery__ticks__tick-locators
0
figure_000.png
Tick locators — Matplotlib 3.10.8 documentation
https://matplotlib.org/stable/gallery/ticks/tick-locators.html#tick-locators
https://matplotlib.org/stable/_downloads/7dd629c030892b8738bc4c5e86dc6736/tick-locators.py
tick-locators.py
ticks
ok
1
null
""" ============================================ Set default y-axis tick labels on the right ============================================ We can use :rc:`ytick.labelright`, :rc:`ytick.right`, :rc:`ytick.labelleft`, and :rc:`ytick.left` to control where on the axes ticks and their labels appear. These properties can also be set in ``.matplotlib/matplotlibrc``. """ import matplotlib.pyplot as plt import numpy as np plt.rcParams['ytick.right'] = plt.rcParams['ytick.labelright'] = True plt.rcParams['ytick.left'] = plt.rcParams['ytick.labelleft'] = False x = np.arange(10) fig, (ax0, ax1) = plt.subplots(2, 1, sharex=True, figsize=(6, 6)) ax0.plot(x) ax0.yaxis.tick_left() # use default parameter in rcParams, not calling tick_right() ax1.plot(x) plt.show()
stable__gallery__ticks__tick_label_right
0
figure_000.png
Set default y-axis tick labels on the right — Matplotlib 3.10.8 documentation
https://matplotlib.org/stable/gallery/ticks/tick_label_right.html#sphx-glr-download-gallery-ticks-tick-label-right-py
https://matplotlib.org/stable/_downloads/e30931f9cdd67ddca47f3c2a7ec762c7/tick_label_right.py
tick_label_right.py
ticks
ok
1
null
""" ========================================= Setting tick labels from a list of values ========================================= Using `.Axes.set_xticks` causes the tick labels to be set on the currently chosen ticks. However, you may want to allow matplotlib to dynamically choose the number of ticks and their spacing. In this case it may be better to determine the tick label from the value at the tick. The following example shows how to do this. NB: The `.ticker.MaxNLocator` is used here to ensure that the tick values take integer values. """ import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator fig, ax = plt.subplots() xs = range(26) ys = range(26) labels = list('abcdefghijklmnopqrstuvwxyz') def format_fn(tick_val, tick_pos): if int(tick_val) in xs: return labels[int(tick_val)] else: return '' # A FuncFormatter is created automatically. ax.xaxis.set_major_formatter(format_fn) ax.xaxis.set_major_locator(MaxNLocator(integer=True)) ax.plot(xs, ys) plt.show() # %% # # .. admonition:: References # # The use of the following functions, methods, classes and modules is shown # in this example: # # - `matplotlib.pyplot.subplots` # - `matplotlib.axis.Axis.set_major_formatter` # - `matplotlib.axis.Axis.set_major_locator` # - `matplotlib.ticker.FuncFormatter` # - `matplotlib.ticker.MaxNLocator`
stable__gallery__ticks__tick_labels_from_values
0
figure_000.png
Setting tick labels from a list of values — Matplotlib 3.10.8 documentation
https://matplotlib.org/stable/gallery/ticks/tick_labels_from_values.html#sphx-glr-download-gallery-ticks-tick-labels-from-values-py
https://matplotlib.org/stable/_downloads/2b7917f5efd95d93b11c49f7a421baeb/tick_labels_from_values.py
tick_labels_from_values.py
ticks
ok
1
null
""" ================================== Move x-axis tick labels to the top ================================== `~.axes.Axes.tick_params` can be used to configure the ticks. *top* and *labeltop* control the visibility tick lines and labels at the top x-axis. To move x-axis ticks from bottom to top, we have to activate the top ticks and deactivate the bottom ticks:: ax.tick_params(top=True, labeltop=True, bottom=False, labelbottom=False) .. note:: If the change should be made for all future plots and not only the current Axes, you can adapt the respective config parameters - :rc:`xtick.top` - :rc:`xtick.labeltop` - :rc:`xtick.bottom` - :rc:`xtick.labelbottom` """ import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.plot(range(10)) ax.tick_params(top=True, labeltop=True, bottom=False, labelbottom=False) ax.set_title('x-ticks moved to the top') plt.show()
stable__gallery__ticks__tick_xlabel_top
0
figure_000.png
Move x-axis tick labels to the top — Matplotlib 3.10.8 documentation
https://matplotlib.org/stable/gallery/ticks/tick_xlabel_top.html#sphx-glr-download-gallery-ticks-tick-xlabel-top-py
https://matplotlib.org/stable/_downloads/3963661c0214fe8afa4aa8c5aa77218e/tick_xlabel_top.py
tick_xlabel_top.py
ticks
ok
1
null
""" =================== Rotated tick labels =================== """ import matplotlib.pyplot as plt x = [1, 2, 3, 4] y = [1, 4, 9, 6] labels = ['Frogs', 'Hogs', 'Bogs', 'Slogs'] fig, ax = plt.subplots() ax.plot(x, y) # A tick label rotation can be set using Axes.tick_params. ax.tick_params("y", rotation=45) # Alternatively, if setting custom labels with set_xticks/set_yticks, it can # be set at the same time as the labels. # For both APIs, the rotation can be an angle in degrees, or one of the strings # "horizontal" or "vertical". ax.set_xticks(x, labels, rotation='vertical') plt.show() # %% # # .. admonition:: References # # The use of the following functions, methods, classes and modules is shown # in this example: # # - `matplotlib.axes.Axes.tick_params` / `matplotlib.pyplot.tick_params` # - `matplotlib.axes.Axes.set_xticks` / `matplotlib.pyplot.xticks`
stable__gallery__ticks__ticklabels_rotation
0
figure_000.png
Rotated tick labels — Matplotlib 3.10.8 documentation
https://matplotlib.org/stable/gallery/ticks/ticklabels_rotation.html#sphx-glr-download-gallery-ticks-ticklabels-rotation-py
https://matplotlib.org/stable/_downloads/6bf1f86ac14b705a7352333c341c3b82/ticklabels_rotation.py
ticklabels_rotation.py
ticks
ok
1
null
""" ===================== Fixing too many ticks ===================== One common cause for unexpected tick behavior is passing a list of strings instead of numbers or datetime objects. This can easily happen without notice when reading in a comma-delimited text file. Matplotlib treats lists of strings as *categorical* variables (:doc:`/gallery/lines_bars_and_markers/categorical_variables`), and by default puts one tick per category, and plots them in the order in which they are supplied. If this is not desired, the solution is to convert the strings to a numeric type as in the following examples. """ # %% # Example 1: Strings can lead to an unexpected order of number ticks # ------------------------------------------------------------------ import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots(1, 2, layout='constrained', figsize=(6, 2.5)) x = ['1', '5', '2', '3'] y = [1, 4, 2, 3] ax[0].plot(x, y, 'd') ax[0].tick_params(axis='x', color='r', labelcolor='r') ax[0].set_xlabel('Categories') ax[0].set_title('Ticks seem out of order / misplaced') # convert to numbers: x = np.asarray(x, dtype='float') ax[1].plot(x, y, 'd') ax[1].set_xlabel('Floats') ax[1].set_title('Ticks as expected') # %% # Example 2: Strings can lead to very many ticks # ---------------------------------------------- # If *x* has 100 elements, all strings, then we would have 100 (unreadable) # ticks, and again the solution is to convert the strings to floats: fig, ax = plt.subplots(1, 2, figsize=(6, 2.5)) x = [f'{xx}' for xx in np.arange(100)] y = np.arange(100) ax[0].plot(x, y) ax[0].tick_params(axis='x', color='r', labelcolor='r') ax[0].set_title('Too many ticks') ax[0].set_xlabel('Categories') ax[1].plot(np.asarray(x, float), y) ax[1].set_title('x converted to numbers') ax[1].set_xlabel('Floats') # %% # Example 3: Strings can lead to an unexpected order of datetime ticks # -------------------------------------------------------------------- # A common case is when dates are read from a CSV file, they need to be # converted from strings to datetime objects to get the proper date locators # and formatters. fig, ax = plt.subplots(1, 2, layout='constrained', figsize=(6, 2.75)) x = ['2021-10-01', '2021-11-02', '2021-12-03', '2021-09-01'] y = [0, 2, 3, 1] ax[0].plot(x, y, 'd') ax[0].tick_params(axis='x', labelrotation=90, color='r', labelcolor='r') ax[0].set_title('Dates out of order') # convert to datetime64 x = np.asarray(x, dtype='datetime64[s]') ax[1].plot(x, y, 'd') ax[1].tick_params(axis='x', labelrotation=90) ax[1].set_title('x converted to datetimes') plt.show()
stable__gallery__ticks__ticks_too_many
0
figure_000.png
Fixing too many ticks — Matplotlib 3.10.8 documentation
https://matplotlib.org/stable/gallery/ticks/ticks_too_many.html#sphx-glr-download-gallery-ticks-ticks-too-many-py
https://matplotlib.org/stable/_downloads/bf27e73826393797c5d906c0afefb14d/ticks_too_many.py
ticks_too_many.py
ticks
ok
3
null
""" ===================== Fixing too many ticks ===================== One common cause for unexpected tick behavior is passing a list of strings instead of numbers or datetime objects. This can easily happen without notice when reading in a comma-delimited text file. Matplotlib treats lists of strings as *categorical* variables (:doc:`/gallery/lines_bars_and_markers/categorical_variables`), and by default puts one tick per category, and plots them in the order in which they are supplied. If this is not desired, the solution is to convert the strings to a numeric type as in the following examples. """ # %% # Example 1: Strings can lead to an unexpected order of number ticks # ------------------------------------------------------------------ import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots(1, 2, layout='constrained', figsize=(6, 2.5)) x = ['1', '5', '2', '3'] y = [1, 4, 2, 3] ax[0].plot(x, y, 'd') ax[0].tick_params(axis='x', color='r', labelcolor='r') ax[0].set_xlabel('Categories') ax[0].set_title('Ticks seem out of order / misplaced') # convert to numbers: x = np.asarray(x, dtype='float') ax[1].plot(x, y, 'd') ax[1].set_xlabel('Floats') ax[1].set_title('Ticks as expected') # %% # Example 2: Strings can lead to very many ticks # ---------------------------------------------- # If *x* has 100 elements, all strings, then we would have 100 (unreadable) # ticks, and again the solution is to convert the strings to floats: fig, ax = plt.subplots(1, 2, figsize=(6, 2.5)) x = [f'{xx}' for xx in np.arange(100)] y = np.arange(100) ax[0].plot(x, y) ax[0].tick_params(axis='x', color='r', labelcolor='r') ax[0].set_title('Too many ticks') ax[0].set_xlabel('Categories') ax[1].plot(np.asarray(x, float), y) ax[1].set_title('x converted to numbers') ax[1].set_xlabel('Floats') # %% # Example 3: Strings can lead to an unexpected order of datetime ticks # -------------------------------------------------------------------- # A common case is when dates are read from a CSV file, they need to be # converted from strings to datetime objects to get the proper date locators # and formatters. fig, ax = plt.subplots(1, 2, layout='constrained', figsize=(6, 2.75)) x = ['2021-10-01', '2021-11-02', '2021-12-03', '2021-09-01'] y = [0, 2, 3, 1] ax[0].plot(x, y, 'd') ax[0].tick_params(axis='x', labelrotation=90, color='r', labelcolor='r') ax[0].set_title('Dates out of order') # convert to datetime64 x = np.asarray(x, dtype='datetime64[s]') ax[1].plot(x, y, 'd') ax[1].tick_params(axis='x', labelrotation=90) ax[1].set_title('x converted to datetimes') plt.show()
stable__gallery__ticks__ticks_too_many
1
figure_001.png
Fixing too many ticks — Matplotlib 3.10.8 documentation
https://matplotlib.org/stable/gallery/ticks/ticks_too_many.html#sphx-glr-download-gallery-ticks-ticks-too-many-py
https://matplotlib.org/stable/_downloads/bf27e73826393797c5d906c0afefb14d/ticks_too_many.py
ticks_too_many.py
ticks
ok
3
null
""" ===================== Fixing too many ticks ===================== One common cause for unexpected tick behavior is passing a list of strings instead of numbers or datetime objects. This can easily happen without notice when reading in a comma-delimited text file. Matplotlib treats lists of strings as *categorical* variables (:doc:`/gallery/lines_bars_and_markers/categorical_variables`), and by default puts one tick per category, and plots them in the order in which they are supplied. If this is not desired, the solution is to convert the strings to a numeric type as in the following examples. """ # %% # Example 1: Strings can lead to an unexpected order of number ticks # ------------------------------------------------------------------ import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots(1, 2, layout='constrained', figsize=(6, 2.5)) x = ['1', '5', '2', '3'] y = [1, 4, 2, 3] ax[0].plot(x, y, 'd') ax[0].tick_params(axis='x', color='r', labelcolor='r') ax[0].set_xlabel('Categories') ax[0].set_title('Ticks seem out of order / misplaced') # convert to numbers: x = np.asarray(x, dtype='float') ax[1].plot(x, y, 'd') ax[1].set_xlabel('Floats') ax[1].set_title('Ticks as expected') # %% # Example 2: Strings can lead to very many ticks # ---------------------------------------------- # If *x* has 100 elements, all strings, then we would have 100 (unreadable) # ticks, and again the solution is to convert the strings to floats: fig, ax = plt.subplots(1, 2, figsize=(6, 2.5)) x = [f'{xx}' for xx in np.arange(100)] y = np.arange(100) ax[0].plot(x, y) ax[0].tick_params(axis='x', color='r', labelcolor='r') ax[0].set_title('Too many ticks') ax[0].set_xlabel('Categories') ax[1].plot(np.asarray(x, float), y) ax[1].set_title('x converted to numbers') ax[1].set_xlabel('Floats') # %% # Example 3: Strings can lead to an unexpected order of datetime ticks # -------------------------------------------------------------------- # A common case is when dates are read from a CSV file, they need to be # converted from strings to datetime objects to get the proper date locators # and formatters. fig, ax = plt.subplots(1, 2, layout='constrained', figsize=(6, 2.75)) x = ['2021-10-01', '2021-11-02', '2021-12-03', '2021-09-01'] y = [0, 2, 3, 1] ax[0].plot(x, y, 'd') ax[0].tick_params(axis='x', labelrotation=90, color='r', labelcolor='r') ax[0].set_title('Dates out of order') # convert to datetime64 x = np.asarray(x, dtype='datetime64[s]') ax[1].plot(x, y, 'd') ax[1].tick_params(axis='x', labelrotation=90) ax[1].set_title('x converted to datetimes') plt.show()
stable__gallery__ticks__ticks_too_many
2
figure_002.png
Fixing too many ticks — Matplotlib 3.10.8 documentation
https://matplotlib.org/stable/gallery/ticks/ticks_too_many.html#sphx-glr-download-gallery-ticks-ticks-too-many-py
https://matplotlib.org/stable/_downloads/bf27e73826393797c5d906c0afefb14d/ticks_too_many.py
ticks_too_many.py
ticks
ok
3
null
""" ========== Evans test ========== A mockup "Foo" units class which supports conversion and different tick formatting depending on the "unit". Here the "unit" is just a scalar conversion factor, but this example shows that Matplotlib is entirely agnostic to what kind of units client packages use. """ import matplotlib.pyplot as plt import numpy as np import matplotlib.ticker as ticker import matplotlib.units as units class Foo: def __init__(self, val, unit=1.0): self.unit = unit self._val = val * unit def value(self, unit): if unit is None: unit = self.unit return self._val / unit class FooConverter(units.ConversionInterface): @staticmethod def axisinfo(unit, axis): """Return the Foo AxisInfo.""" if unit == 1.0 or unit == 2.0: return units.AxisInfo( majloc=ticker.IndexLocator(8, 0), majfmt=ticker.FormatStrFormatter("VAL: %s"), label='foo', ) else: return None @staticmethod def convert(obj, unit, axis): """ Convert *obj* using *unit*. If *obj* is a sequence, return the converted sequence. """ if np.iterable(obj): return [o.value(unit) for o in obj] else: return obj.value(unit) @staticmethod def default_units(x, axis): """Return the default unit for *x* or None.""" if np.iterable(x): for thisx in x: return thisx.unit else: return x.unit units.registry[Foo] = FooConverter() # create some Foos x = [Foo(val, 1.0) for val in range(0, 50, 2)] # and some arbitrary y data y = [i for i in range(len(x))] fig, (ax1, ax2) = plt.subplots(1, 2) fig.suptitle("Custom units") fig.subplots_adjust(bottom=0.2) # plot specifying units ax2.plot(x, y, 'o', xunits=2.0) ax2.set_title("xunits = 2.0") plt.setp(ax2.get_xticklabels(), rotation=30, ha='right') # plot without specifying units; will use the None branch for axisinfo ax1.plot(x, y) # uses default units ax1.set_title('default units') plt.setp(ax1.get_xticklabels(), rotation=30, ha='right') plt.show()
stable__gallery__units__evans_test
0
figure_000.png
Evans test — Matplotlib 3.10.8 documentation
https://matplotlib.org/stable/gallery/units/evans_test.html#sphx-glr-download-gallery-units-evans-test-py
https://matplotlib.org/stable/_downloads/dd53845e9b4ff2a1c978459bd05b003e/evans_test.py
evans_test.py
units
ok
1
null
""" ============= SVG Histogram ============= Demonstrate how to create an interactive histogram, in which bars are hidden or shown by clicking on legend markers. The interactivity is encoded in ecmascript (javascript) and inserted in the SVG code in a post-processing step. To render the image, open it in a web browser. SVG is supported in most web browsers used by Linux and macOS users. Windows IE9 supports SVG, but earlier versions do not. Notes ----- The matplotlib backend lets us assign ids to each object. This is the mechanism used here to relate matplotlib objects created in python and the corresponding SVG constructs that are parsed in the second step. While flexible, ids are cumbersome to use for large collection of objects. Two mechanisms could be used to simplify things: * systematic grouping of objects into SVG <g> tags, * assigning classes to each SVG object according to its origin. For example, instead of modifying the properties of each individual bar, the bars from the `~.pyplot.hist` function could either be grouped in a PatchCollection, or be assigned a class="hist_##" attribute. CSS could also be used more extensively to replace repetitive markup throughout the generated SVG. Author: david.huard@gmail.com """ from io import BytesIO import json import xml.etree.ElementTree as ET import matplotlib.pyplot as plt import numpy as np plt.rcParams['svg.fonttype'] = 'none' # Apparently, this `register_namespace` method is necessary to avoid garbling # the XML namespace with ns0. ET.register_namespace("", "http://www.w3.org/2000/svg") # Fixing random state for reproducibility np.random.seed(19680801) # --- Create histogram, legend and title --- plt.figure() r = np.random.randn(100) r1 = r + 1 labels = ['Rabbits', 'Frogs'] H = plt.hist([r, r1], label=labels) containers = H[-1] leg = plt.legend(frameon=False) plt.title("From a web browser, click on the legend\n" "marker to toggle the corresponding histogram.") # --- Add ids to the svg objects we'll modify hist_patches = {} for ic, c in enumerate(containers): hist_patches[f'hist_{ic}'] = [] for il, element in enumerate(c): element.set_gid(f'hist_{ic}_patch_{il}') hist_patches[f'hist_{ic}'].append(f'hist_{ic}_patch_{il}') # Set ids for the legend patches for i, t in enumerate(leg.get_patches()): t.set_gid(f'leg_patch_{i}') # Set ids for the text patches for i, t in enumerate(leg.get_texts()): t.set_gid(f'leg_text_{i}') # Save SVG in a fake file object. f = BytesIO() plt.savefig(f, format="svg") # Create XML tree from the SVG file. tree, xmlid = ET.XMLID(f.getvalue()) # --- Add interactivity --- # Add attributes to the patch objects. for i, t in enumerate(leg.get_patches()): el = xmlid[f'leg_patch_{i}'] el.set('cursor', 'pointer') el.set('onclick', "toggle_hist(this)") # Add attributes to the text objects. for i, t in enumerate(leg.get_texts()): el = xmlid[f'leg_text_{i}'] el.set('cursor', 'pointer') el.set('onclick', "toggle_hist(this)") # Create script defining the function `toggle_hist`. # We create a global variable `container` that stores the patches id # belonging to each histogram. Then a function "toggle_element" sets the # visibility attribute of all patches of each histogram and the opacity # of the marker itself. script = """ <script type="text/ecmascript"> <![CDATA[ var container = %s function toggle(oid, attribute, values) { /* Toggle the style attribute of an object between two values. Parameters ---------- oid : str Object identifier. attribute : str Name of style attribute. values : [on state, off state] The two values that are switched between. */ var obj = document.getElementById(oid); var a = obj.style[attribute]; a = (a == values[0] || a == "") ? values[1] : values[0]; obj.style[attribute] = a; } function toggle_hist(obj) { var num = obj.id.slice(-1); toggle('leg_patch_' + num, 'opacity', [1, 0.3]); toggle('leg_text_' + num, 'opacity', [1, 0.5]); var names = container['hist_'+num] for (var i=0; i < names.length; i++) { toggle(names[i], 'opacity', [1, 0]) }; } ]]> </script> """ % json.dumps(hist_patches) # Add a transition effect css = tree.find('.//{http://www.w3.org/2000/svg}style') css.text = css.text + "g {-webkit-transition:opacity 0.4s ease-out;" + \ "-moz-transition:opacity 0.4s ease-out;}" # Insert the script and save to file. tree.insert(0, ET.XML(script)) ET.ElementTree(tree).write("svg_histogram.svg")
stable__gallery__user_interfaces__svg_histogram_sgskip
0
figure_000.png
SVG Histogram — Matplotlib 3.10.8 documentation
https://matplotlib.org/stable/gallery/user_interfaces/svg_histogram_sgskip.html#svg-histogram
https://matplotlib.org/stable/_downloads/dbbfc471cc5f69a894fff87dbd2bbf19/svg_histogram_sgskip.py
svg_histogram_sgskip.py
user_interfaces
ok
1
null
""" =========== SVG Tooltip =========== This example shows how to create a tooltip that will show up when hovering over a matplotlib patch. Although it is possible to create the tooltip from CSS or javascript, here we create it in matplotlib and simply toggle its visibility on when hovering over the patch. This approach provides total control over the tooltip placement and appearance, at the expense of more code up front. The alternative approach would be to put the tooltip content in ``title`` attributes of SVG objects. Then, using an existing js/CSS library, it would be relatively straightforward to create the tooltip in the browser. The content would be dictated by the ``title`` attribute, and the appearance by the CSS. :author: David Huard """ from io import BytesIO import xml.etree.ElementTree as ET import matplotlib.pyplot as plt ET.register_namespace("", "http://www.w3.org/2000/svg") fig, ax = plt.subplots() # Create patches to which tooltips will be assigned. rect1 = plt.Rectangle((10, -20), 10, 5, fc='blue') rect2 = plt.Rectangle((-20, 15), 10, 5, fc='green') shapes = [rect1, rect2] labels = ['This is a blue rectangle.', 'This is a green rectangle'] for i, (item, label) in enumerate(zip(shapes, labels)): patch = ax.add_patch(item) annotate = ax.annotate(labels[i], xy=item.get_xy(), xytext=(0, 0), textcoords='offset points', color='w', ha='center', fontsize=8, bbox=dict(boxstyle='round, pad=.5', fc=(.1, .1, .1, .92), ec=(1., 1., 1.), lw=1, zorder=1)) ax.add_patch(patch) patch.set_gid(f'mypatch_{i:03d}') annotate.set_gid(f'mytooltip_{i:03d}') # Save the figure in a fake file object ax.set_xlim(-30, 30) ax.set_ylim(-30, 30) ax.set_aspect('equal') f = BytesIO() plt.savefig(f, format="svg") # --- Add interactivity --- # Create XML tree from the SVG file. tree, xmlid = ET.XMLID(f.getvalue()) tree.set('onload', 'init(event)') for i in shapes: # Get the index of the shape index = shapes.index(i) # Hide the tooltips tooltip = xmlid[f'mytooltip_{index:03d}'] tooltip.set('visibility', 'hidden') # Assign onmouseover and onmouseout callbacks to patches. mypatch = xmlid[f'mypatch_{index:03d}'] mypatch.set('onmouseover', "ShowTooltip(this)") mypatch.set('onmouseout', "HideTooltip(this)") # This is the script defining the ShowTooltip and HideTooltip functions. script = """ <script type="text/ecmascript"> <![CDATA[ function init(event) { if ( window.svgDocument == null ) { svgDocument = event.target.ownerDocument; } } function ShowTooltip(obj) { var cur = obj.id.split("_")[1]; var tip = svgDocument.getElementById('mytooltip_' + cur); tip.setAttribute('visibility', "visible") } function HideTooltip(obj) { var cur = obj.id.split("_")[1]; var tip = svgDocument.getElementById('mytooltip_' + cur); tip.setAttribute('visibility', "hidden") } ]]> </script> """ # Insert the script at the top of the file and save it. tree.insert(0, ET.XML(script)) ET.ElementTree(tree).write('svg_tooltip.svg')
stable__gallery__user_interfaces__svg_tooltip_sgskip
0
figure_000.png
SVG Tooltip — Matplotlib 3.10.8 documentation
https://matplotlib.org/stable/gallery/user_interfaces/svg_tooltip_sgskip.html#svg-tooltip
https://matplotlib.org/stable/_downloads/b1d72b68be293db9dab6f77187a06e16/svg_tooltip_sgskip.py
svg_tooltip_sgskip.py
user_interfaces
ok
1
null
r""" ================ Nested GridSpecs ================ This example demonstrates the use of nested `.GridSpec`\s. """ import matplotlib.pyplot as plt import numpy as np def squiggle_xy(a, b, c, d): i = np.arange(0.0, 2*np.pi, 0.05) return np.sin(i*a)*np.cos(i*b), np.sin(i*c)*np.cos(i*d) fig = plt.figure(figsize=(8, 8)) outer_grid = fig.add_gridspec(4, 4, wspace=0, hspace=0) for a in range(4): for b in range(4): # gridspec inside gridspec inner_grid = outer_grid[a, b].subgridspec(3, 3, wspace=0, hspace=0) axs = inner_grid.subplots() # Create all subplots for the inner grid. for (c, d), ax in np.ndenumerate(axs): ax.plot(*squiggle_xy(a + 1, b + 1, c + 1, d + 1)) ax.set(xticks=[], yticks=[]) # show only the outside spines for ax in fig.get_axes(): ss = ax.get_subplotspec() ax.spines.top.set_visible(ss.is_first_row()) ax.spines.bottom.set_visible(ss.is_last_row()) ax.spines.left.set_visible(ss.is_first_col()) ax.spines.right.set_visible(ss.is_last_col()) plt.show()
stable__gallery__userdemo__demo_gridspec06
0
figure_000.png
Nested GridSpecs — Matplotlib 3.10.8 documentation
https://matplotlib.org/stable/gallery/userdemo/demo_gridspec06.html#sphx-glr-download-gallery-userdemo-demo-gridspec06-py
https://matplotlib.org/stable/_downloads/82f0e1275a063ac077b19c2162ab5453/demo_gridspec06.py
demo_gridspec06.py
userdemo
ok
1
null
""" =============== Simple Legend01 =============== """ import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(211) ax.plot([1, 2, 3], label="test1") ax.plot([3, 2, 1], label="test2") # Place a legend above this subplot, expanding itself to # fully use the given bounding box. ax.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc='lower left', ncols=2, mode="expand", borderaxespad=0.) ax = fig.add_subplot(223) ax.plot([1, 2, 3], label="test1") ax.plot([3, 2, 1], label="test2") # Place a legend to the right of this smaller subplot. ax.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0.) plt.show()
stable__gallery__userdemo__simple_legend01
0
figure_000.png
Simple Legend01 — Matplotlib 3.10.8 documentation
https://matplotlib.org/stable/gallery/userdemo/simple_legend01.html#sphx-glr-download-gallery-userdemo-simple-legend01-py
https://matplotlib.org/stable/_downloads/4e35546e054302909f70da22e48450ec/simple_legend01.py
simple_legend01.py
userdemo
ok
1
null
""" =============== Simple Legend02 =============== """ import matplotlib.pyplot as plt fig, ax = plt.subplots() line1, = ax.plot([1, 2, 3], label="Line 1", linestyle='--') line2, = ax.plot([3, 2, 1], label="Line 2", linewidth=4) # Create a legend for the first line. first_legend = ax.legend(handles=[line1], loc='upper right') # Add the legend manually to the current Axes. ax.add_artist(first_legend) # Create another legend for the second line. ax.legend(handles=[line2], loc='lower right') plt.show()
stable__gallery__userdemo__simple_legend02
0
figure_000.png
Simple Legend02 — Matplotlib 3.10.8 documentation
https://matplotlib.org/stable/gallery/userdemo/simple_legend02.html#sphx-glr-download-gallery-userdemo-simple-legend02-py
https://matplotlib.org/stable/_downloads/a28765be19887476469c03569a192293/simple_legend02.py
simple_legend02.py
userdemo
ok
1
null
""" ================ Annotated cursor ================ Display a data cursor including a text box, which shows the plot point close to the mouse pointer. The new cursor inherits from `~matplotlib.widgets.Cursor` and demonstrates the creation of new widgets and their event callbacks. See also the :doc:`cross hair cursor </gallery/event_handling/cursor_demo>`, which implements a cursor tracking the plotted data, but without using inheritance and without displaying the currently tracked coordinates. .. note:: The figure related to this example does not show the cursor, because that figure is automatically created in a build queue, where the first mouse movement, which triggers the cursor creation, is missing. """ import matplotlib.pyplot as plt import numpy as np from matplotlib.backend_bases import MouseEvent from matplotlib.widgets import Cursor class AnnotatedCursor(Cursor): """ A crosshair cursor like `~matplotlib.widgets.Cursor` with a text showing \ the current coordinates. For the cursor to remain responsive you must keep a reference to it. The data of the axis specified as *dataaxis* must be in ascending order. Otherwise, the `numpy.searchsorted` call might fail and the text disappears. You can satisfy the requirement by sorting the data you plot. Usually the data is already sorted (if it was created e.g. using `numpy.linspace`), but e.g. scatter plots might cause this problem. The cursor sticks to the plotted line. Parameters ---------- line : `matplotlib.lines.Line2D` The plot line from which the data coordinates are displayed. numberformat : `python format string <https://docs.python.org/3/\ library/string.html#formatstrings>`_, optional, default: "{0:.4g};{1:.4g}" The displayed text is created by calling *format()* on this string with the two coordinates. offset : (float, float) default: (5, 5) The offset in display (pixel) coordinates of the text position relative to the cross-hair. dataaxis : {"x", "y"}, optional, default: "x" If "x" is specified, the vertical cursor line sticks to the mouse pointer. The horizontal cursor line sticks to *line* at that x value. The text shows the data coordinates of *line* at the pointed x value. If you specify "y", it works in the opposite manner. But: For the "y" value, where the mouse points to, there might be multiple matching x values, if the plotted function is not biunique. Cursor and text coordinate will always refer to only one x value. So if you use the parameter value "y", ensure that your function is biunique. Other Parameters ---------------- textprops : `matplotlib.text` properties as dictionary Specifies the appearance of the rendered text object. **cursorargs : `matplotlib.widgets.Cursor` properties Arguments passed to the internal `~matplotlib.widgets.Cursor` instance. The `matplotlib.axes.Axes` argument is mandatory! The parameter *useblit* can be set to *True* in order to achieve faster rendering. """ def __init__(self, line, numberformat="{0:.4g};{1:.4g}", offset=(5, 5), dataaxis='x', textprops=None, **cursorargs): if textprops is None: textprops = {} # The line object, for which the coordinates are displayed self.line = line # The format string, on which .format() is called for creating the text self.numberformat = numberformat # Text position offset self.offset = np.array(offset) # The axis in which the cursor position is looked up self.dataaxis = dataaxis # First call baseclass constructor. # Draws cursor and remembers background for blitting. # Saves ax as class attribute. super().__init__(**cursorargs) # Default value for position of text. self.set_position(self.line.get_xdata()[0], self.line.get_ydata()[0]) # Create invisible animated text self.text = self.ax.text( self.ax.get_xbound()[0], self.ax.get_ybound()[0], "0, 0", animated=bool(self.useblit), visible=False, **textprops) # The position at which the cursor was last drawn self.lastdrawnplotpoint = None def onmove(self, event): """ Overridden draw callback for cursor. Called when moving the mouse. """ # Leave method under the same conditions as in overridden method if self.ignore(event): self.lastdrawnplotpoint = None return if not self.canvas.widgetlock.available(self): self.lastdrawnplotpoint = None return # If the mouse left drawable area, we now make the text invisible. # Baseclass will redraw complete canvas after, which makes both text # and cursor disappear. if event.inaxes != self.ax: self.lastdrawnplotpoint = None self.text.set_visible(False) super().onmove(event) return # Get the coordinates, which should be displayed as text, # if the event coordinates are valid. plotpoint = None if event.xdata is not None and event.ydata is not None: # Get plot point related to current x position. # These coordinates are displayed in text. plotpoint = self.set_position(event.xdata, event.ydata) # Modify event, such that the cursor is displayed on the # plotted line, not at the mouse pointer, # if the returned plot point is valid if plotpoint is not None: event.xdata = plotpoint[0] event.ydata = plotpoint[1] # If the plotpoint is given, compare to last drawn plotpoint and # return if they are the same. # Skip even the call of the base class, because this would restore the # background, draw the cursor lines and would leave us the job to # re-draw the text. if plotpoint is not None and plotpoint == self.lastdrawnplotpoint: return # Baseclass redraws canvas and cursor. Due to blitting, # the added text is removed in this call, because the # background is redrawn. super().onmove(event) # Check if the display of text is still necessary. # If not, just return. # This behaviour is also cloned from the base class. if not self.get_active() or not self.visible: return # Draw the widget, if event coordinates are valid. if plotpoint is not None: # Update position and displayed text. # Position: Where the event occurred. # Text: Determined by set_position() method earlier # Position is transformed to pixel coordinates, # an offset is added there and this is transformed back. temp = [event.xdata, event.ydata] temp = self.ax.transData.transform(temp) temp = temp + self.offset temp = self.ax.transData.inverted().transform(temp) self.text.set_position(temp) self.text.set_text(self.numberformat.format(*plotpoint)) self.text.set_visible(self.visible) # Tell base class, that we have drawn something. # Baseclass needs to know, that it needs to restore a clean # background, if the cursor leaves our figure context. self.needclear = True # Remember the recently drawn cursor position, so events for the # same position (mouse moves slightly between two plot points) # can be skipped self.lastdrawnplotpoint = plotpoint # otherwise, make text invisible else: self.text.set_visible(False) # Draw changes. Cannot use _update method of baseclass, # because it would first restore the background, which # is done already and is not necessary. if self.useblit: self.ax.draw_artist(self.text) self.canvas.blit(self.ax.bbox) else: # If blitting is deactivated, the overridden _update call made # by the base class immediately returned. # We still have to draw the changes. self.canvas.draw_idle() def set_position(self, xpos, ypos): """ Finds the coordinates, which have to be shown in text. The behaviour depends on the *dataaxis* attribute. Function looks up the matching plot coordinate for the given mouse position. Parameters ---------- xpos : float The current x position of the cursor in data coordinates. Important if *dataaxis* is set to 'x'. ypos : float The current y position of the cursor in data coordinates. Important if *dataaxis* is set to 'y'. Returns ------- ret : {2D array-like, None} The coordinates which should be displayed. *None* is the fallback value. """ # Get plot line data xdata = self.line.get_xdata() ydata = self.line.get_ydata() # The dataaxis attribute decides, in which axis we look up which cursor # coordinate. if self.dataaxis == 'x': pos = xpos data = xdata lim = self.ax.get_xlim() elif self.dataaxis == 'y': pos = ypos data = ydata lim = self.ax.get_ylim() else: raise ValueError(f"The data axis specifier {self.dataaxis} should " f"be 'x' or 'y'") # If position is valid and in valid plot data range. if pos is not None and lim[0] <= pos <= lim[-1]: # Find closest x value in sorted x vector. # This requires the plotted data to be sorted. index = np.searchsorted(data, pos) # Return none, if this index is out of range. if index < 0 or index >= len(data): return None # Return plot point as tuple. return (xdata[index], ydata[index]) # Return none if there is no good related point for this x position. return None def clear(self, event): """ Overridden clear callback for cursor, called before drawing the figure. """ # The base class saves the clean background for blitting. # Text and cursor are invisible, # until the first mouse move event occurs. super().clear(event) if self.ignore(event): return self.text.set_visible(False) def _update(self): """ Overridden method for either blitting or drawing the widget canvas. Passes call to base class if blitting is activated, only. In other cases, one draw_idle call is enough, which is placed explicitly in this class (see *onmove()*). In that case, `~matplotlib.widgets.Cursor` is not supposed to draw something using this method. """ if self.useblit: super()._update() fig, ax = plt.subplots(figsize=(8, 6)) ax.set_title("Cursor Tracking x Position") x = np.linspace(-5, 5, 1000) y = x**2 line, = ax.plot(x, y) ax.set_xlim(-5, 5) ax.set_ylim(0, 25) # A minimum call # Set useblit=True on most backends for enhanced performance # and pass the ax parameter to the Cursor base class. # cursor = AnnotatedCursor(line=lin[0], ax=ax, useblit=True) # A more advanced call. Properties for text and lines are passed. # Watch the passed color names and the color of cursor line and text, to # relate the passed options to graphical elements. # The dataaxis parameter is still the default. cursor = AnnotatedCursor( line=line, numberformat="{0:.2f}\n{1:.2f}", dataaxis='x', offset=[10, 10], textprops={'color': 'blue', 'fontweight': 'bold'}, ax=ax, useblit=True, color='red', linewidth=2) # Simulate a mouse move to (-2, 10), needed for online docs t = ax.transData MouseEvent( "motion_notify_event", ax.figure.canvas, *t.transform((-2, 10)) )._process() plt.show() # %% # Trouble with non-biunique functions # ----------------------------------- # A call demonstrating problems with the *dataaxis=y* parameter. # The text now looks up the matching x value for the current cursor y position # instead of vice versa. Hover your cursor to y=4. There are two x values # producing this y value: -2 and 2. The function is only unique, # but not biunique. Only one value is shown in the text. fig, ax = plt.subplots(figsize=(8, 6)) ax.set_title("Cursor Tracking y Position") line, = ax.plot(x, y) ax.set_xlim(-5, 5) ax.set_ylim(0, 25) cursor = AnnotatedCursor( line=line, numberformat="{0:.2f}\n{1:.2f}", dataaxis='y', offset=[10, 10], textprops={'color': 'blue', 'fontweight': 'bold'}, ax=ax, useblit=True, color='red', linewidth=2) # Simulate a mouse move to (-2, 10), needed for online docs t = ax.transData MouseEvent( "motion_notify_event", ax.figure.canvas, *t.transform((-2, 10)) )._process() plt.show()
stable__gallery__widgets__annotated_cursor
0
figure_000.png
Annotated cursor — Matplotlib 3.10.8 documentation
https://matplotlib.org/stable/gallery/widgets/annotated_cursor.html#trouble-with-non-biunique-functions
https://matplotlib.org/stable/_downloads/49afaefa9a6da5dbbf0e8baa083505f3/annotated_cursor.py
annotated_cursor.py
widgets
ok
2
null
""" ======= Buttons ======= Constructing a simple button GUI to modify a sine wave. The ``next`` and ``previous`` button widget helps visualize the wave with new frequencies. """ import matplotlib.pyplot as plt import numpy as np from matplotlib.widgets import Button freqs = np.arange(2, 20, 3) fig, ax = plt.subplots() fig.subplots_adjust(bottom=0.2) t = np.arange(0.0, 1.0, 0.001) s = np.sin(2*np.pi*freqs[0]*t) l, = ax.plot(t, s, lw=2) class Index: ind = 0 def next(self, event): self.ind += 1 i = self.ind % len(freqs) ydata = np.sin(2*np.pi*freqs[i]*t) l.set_ydata(ydata) plt.draw() def prev(self, event): self.ind -= 1 i = self.ind % len(freqs) ydata = np.sin(2*np.pi*freqs[i]*t) l.set_ydata(ydata) plt.draw() callback = Index() axprev = fig.add_axes([0.7, 0.05, 0.1, 0.075]) axnext = fig.add_axes([0.81, 0.05, 0.1, 0.075]) bnext = Button(axnext, 'Next') bnext.on_clicked(callback.next) bprev = Button(axprev, 'Previous') bprev.on_clicked(callback.prev) plt.show() # %% # # .. admonition:: References # # The use of the following functions, methods, classes and modules is shown # in this example: # # - `matplotlib.widgets.Button`
stable__gallery__widgets__buttons
0
figure_000.png
Buttons — Matplotlib 3.10.8 documentation
https://matplotlib.org/stable/gallery/widgets/buttons.html#sphx-glr-download-gallery-widgets-buttons-py
https://matplotlib.org/stable/_downloads/1396177ce1d23fee4cbc40e2635021b2/buttons.py
buttons.py
widgets
ok
1
null
""" ============= Check buttons ============= Turning visual elements on and off with check buttons. This program shows the use of `.CheckButtons` which is similar to check boxes. There are 3 different sine waves shown, and we can choose which waves are displayed with the check buttons. Check buttons may be styled using the *check_props*, *frame_props*, and *label_props* parameters. The parameters each take a dictionary with keys of artist property names and values of lists of settings with length matching the number of buttons. """ import matplotlib.pyplot as plt import numpy as np from matplotlib.widgets import CheckButtons t = np.arange(0.0, 2.0, 0.01) s0 = np.sin(2*np.pi*t) s1 = np.sin(4*np.pi*t) s2 = np.sin(6*np.pi*t) fig, ax = plt.subplots() l0, = ax.plot(t, s0, visible=False, lw=2, color='black', label='1 Hz') l1, = ax.plot(t, s1, lw=2, color='red', label='2 Hz') l2, = ax.plot(t, s2, lw=2, color='green', label='3 Hz') lines_by_label = {l.get_label(): l for l in [l0, l1, l2]} line_colors = [l.get_color() for l in lines_by_label.values()] # Make checkbuttons with all plotted lines with correct visibility rax = ax.inset_axes([0.0, 0.0, 0.12, 0.2]) check = CheckButtons( ax=rax, labels=lines_by_label.keys(), actives=[l.get_visible() for l in lines_by_label.values()], label_props={'color': line_colors}, frame_props={'edgecolor': line_colors}, check_props={'facecolor': line_colors}, ) def callback(label): ln = lines_by_label[label] ln.set_visible(not ln.get_visible()) ln.figure.canvas.draw_idle() check.on_clicked(callback) plt.show() # %% # # .. admonition:: References # # The use of the following functions, methods, classes and modules is shown # in this example: # # - `matplotlib.widgets.CheckButtons`
stable__gallery__widgets__check_buttons
0
figure_000.png
Check buttons — Matplotlib 3.10.8 documentation
https://matplotlib.org/stable/gallery/widgets/check_buttons.html#sphx-glr-download-gallery-widgets-check-buttons-py
https://matplotlib.org/stable/_downloads/c08881ff905bac0ced64da581a650859/check_buttons.py
check_buttons.py
widgets
ok
1
null
""" ====== Cursor ====== """ import matplotlib.pyplot as plt import numpy as np from matplotlib.widgets import Cursor # Fixing random state for reproducibility np.random.seed(19680801) fig, ax = plt.subplots(figsize=(8, 6)) x, y = 4*(np.random.rand(2, 100) - .5) ax.plot(x, y, 'o') ax.set_xlim(-2, 2) ax.set_ylim(-2, 2) # Set useblit=True on most backends for enhanced performance. cursor = Cursor(ax, useblit=True, color='red', linewidth=2) plt.show() # %% # # .. admonition:: References # # The use of the following functions, methods, classes and modules is shown # in this example: # # - `matplotlib.widgets.Cursor`
stable__gallery__widgets__cursor
0
figure_000.png
Cursor — Matplotlib 3.10.8 documentation
https://matplotlib.org/stable/gallery/widgets/cursor.html#sphx-glr-download-gallery-widgets-cursor-py
https://matplotlib.org/stable/_downloads/b9ef6f84d8dd108e5700bbf0e163014a/cursor.py
cursor.py
widgets
ok
1
null
""" ============== Lasso Selector ============== Interactively selecting data points with the lasso tool. This examples plots a scatter plot. You can then select a few points by drawing a lasso loop around the points on the graph. To draw, just click on the graph, hold, and drag it around the points you need to select. """ import numpy as np from matplotlib.path import Path from matplotlib.widgets import LassoSelector class SelectFromCollection: """ Select indices from a matplotlib collection using `LassoSelector`. Selected indices are saved in the `ind` attribute. This tool fades out the points that are not part of the selection (i.e., reduces their alpha values). If your collection has alpha < 1, this tool will permanently alter the alpha values. Note that this tool selects collection objects based on their *origins* (i.e., `offsets`). Parameters ---------- ax : `~matplotlib.axes.Axes` Axes to interact with. collection : `matplotlib.collections.Collection` subclass Collection you want to select from. alpha_other : 0 <= float <= 1 To highlight a selection, this tool sets all selected points to an alpha value of 1 and non-selected points to *alpha_other*. """ def __init__(self, ax, collection, alpha_other=0.3): self.canvas = ax.figure.canvas self.collection = collection self.alpha_other = alpha_other self.xys = collection.get_offsets() self.Npts = len(self.xys) # Ensure that we have separate colors for each object self.fc = collection.get_facecolors() if len(self.fc) == 0: raise ValueError('Collection must have a facecolor') elif len(self.fc) == 1: self.fc = np.tile(self.fc, (self.Npts, 1)) self.lasso = LassoSelector(ax, onselect=self.onselect) self.ind = [] def onselect(self, verts): path = Path(verts) self.ind = np.nonzero(path.contains_points(self.xys))[0] self.fc[:, -1] = self.alpha_other self.fc[self.ind, -1] = 1 self.collection.set_facecolors(self.fc) self.canvas.draw_idle() def disconnect(self): self.lasso.disconnect_events() self.fc[:, -1] = 1 self.collection.set_facecolors(self.fc) self.canvas.draw_idle() if __name__ == '__main__': import matplotlib.pyplot as plt # Fixing random state for reproducibility np.random.seed(19680801) data = np.random.rand(100, 2) subplot_kw = dict(xlim=(0, 1), ylim=(0, 1), autoscale_on=False) fig, ax = plt.subplots(subplot_kw=subplot_kw) pts = ax.scatter(data[:, 0], data[:, 1], s=80) selector = SelectFromCollection(ax, pts) def accept(event): if event.key == "enter": print("Selected points:") print(selector.xys[selector.ind]) selector.disconnect() ax.set_title("") fig.canvas.draw() fig.canvas.mpl_connect("key_press_event", accept) ax.set_title("Press enter to accept selected points.") plt.show() # %% # # .. admonition:: References # # The use of the following functions, methods, classes and modules is shown # in this example: # # - `matplotlib.widgets.LassoSelector` # - `matplotlib.path.Path`
stable__gallery__widgets__lasso_selector_demo_sgskip
0
figure_000.png
Lasso Selector — Matplotlib 3.10.8 documentation
https://matplotlib.org/stable/gallery/widgets/lasso_selector_demo_sgskip.html#sphx-glr-download-gallery-widgets-lasso-selector-demo-sgskip-py
https://matplotlib.org/stable/_downloads/cff0c57a9f43e62cbd6e2ee706caa49e/lasso_selector_demo_sgskip.py
lasso_selector_demo_sgskip.py
widgets
ok
1
null
""" ==== Menu ==== Using texts to construct a simple menu. """ from dataclasses import dataclass import matplotlib.pyplot as plt import matplotlib.artist as artist import matplotlib.patches as patches from matplotlib.typing import ColorType @dataclass class ItemProperties: fontsize: float = 14 labelcolor: ColorType = 'black' bgcolor: ColorType = 'yellow' alpha: float = 1.0 class MenuItem(artist.Artist): padx = 0.05 # inches pady = 0.05 def __init__(self, fig, labelstr, props=None, hoverprops=None, on_select=None): super().__init__() self.set_figure(fig) self.labelstr = labelstr self.props = props if props is not None else ItemProperties() self.hoverprops = ( hoverprops if hoverprops is not None else ItemProperties()) if self.props.fontsize != self.hoverprops.fontsize: raise NotImplementedError( 'support for different font sizes not implemented') self.on_select = on_select # specify coordinates in inches. self.label = fig.text(0, 0, labelstr, transform=fig.dpi_scale_trans, size=props.fontsize) self.text_bbox = self.label.get_window_extent( fig.canvas.get_renderer()) self.text_bbox = fig.dpi_scale_trans.inverted().transform_bbox(self.text_bbox) self.rect = patches.Rectangle( (0, 0), 1, 1, transform=fig.dpi_scale_trans ) # Will be updated later. self.set_hover_props(False) fig.canvas.mpl_connect('button_release_event', self.check_select) def check_select(self, event): over, _ = self.rect.contains(event) if not over: return if self.on_select is not None: self.on_select(self) def set_extent(self, x, y, w, h, depth): self.rect.set(x=x, y=y, width=w, height=h) self.label.set(position=(x + self.padx, y + depth + self.pady / 2)) self.hover = False def draw(self, renderer): self.rect.draw(renderer) self.label.draw(renderer) def set_hover_props(self, b): props = self.hoverprops if b else self.props self.label.set(color=props.labelcolor) self.rect.set(facecolor=props.bgcolor, alpha=props.alpha) def set_hover(self, event): """ Update the hover status of event and return whether it was changed. """ b, _ = self.rect.contains(event) changed = (b != self.hover) if changed: self.set_hover_props(b) self.hover = b return changed class Menu: def __init__(self, fig, menuitems): self.figure = fig self.menuitems = menuitems maxw = max(item.text_bbox.width for item in menuitems) maxh = max(item.text_bbox.height for item in menuitems) depth = max(-item.text_bbox.y0 for item in menuitems) x0 = 1 y0 = 4 width = maxw + 2 * MenuItem.padx height = maxh + MenuItem.pady for item in menuitems: left = x0 bottom = y0 - maxh - MenuItem.pady item.set_extent(left, bottom, width, height, depth) fig.artists.append(item) y0 -= maxh + MenuItem.pady fig.canvas.mpl_connect('motion_notify_event', self.on_move) def on_move(self, event): if any(item.set_hover(event) for item in self.menuitems): self.figure.canvas.draw() fig = plt.figure() fig.subplots_adjust(left=0.3) props = ItemProperties(labelcolor='black', bgcolor='yellow', fontsize=15, alpha=0.2) hoverprops = ItemProperties(labelcolor='white', bgcolor='blue', fontsize=15, alpha=0.2) menuitems = [] for label in ('open', 'close', 'save', 'save as', 'quit'): def on_select(item): print(f'you selected {item.labelstr}') item = MenuItem(fig, label, props=props, hoverprops=hoverprops, on_select=on_select) menuitems.append(item) menu = Menu(fig, menuitems) plt.show()
stable__gallery__widgets__menu
0
figure_000.png
Menu — Matplotlib 3.10.8 documentation
https://matplotlib.org/stable/gallery/widgets/menu.html#sphx-glr-download-gallery-widgets-menu-py
https://matplotlib.org/stable/_downloads/1d795d2dbb3742249ef04dbbdc524568/menu.py
menu.py
widgets
ok
1
null
""" ============ Mouse Cursor ============ This example sets an alternative cursor on a figure canvas. Note, this is an interactive example, and must be run to see the effect. """ import matplotlib.pyplot as plt from matplotlib.backend_tools import Cursors fig, axs = plt.subplots(len(Cursors), figsize=(6, len(Cursors) + 0.5), gridspec_kw={'hspace': 0}) fig.suptitle('Hover over an Axes to see alternate Cursors') for cursor, ax in zip(Cursors, axs): ax.cursor_to_use = cursor ax.text(0.5, 0.5, cursor.name, horizontalalignment='center', verticalalignment='center') ax.set(xticks=[], yticks=[]) def hover(event): if fig.canvas.widgetlock.locked(): # Don't do anything if the zoom/pan tools have been enabled. return fig.canvas.set_cursor( event.inaxes.cursor_to_use if event.inaxes else Cursors.POINTER) fig.canvas.mpl_connect('motion_notify_event', hover) plt.show() # %% # # .. admonition:: References # # The use of the following functions, methods, classes and modules is shown # in this example: # # - `matplotlib.backend_bases.FigureCanvasBase.set_cursor`
stable__gallery__widgets__mouse_cursor
0
figure_000.png
Mouse Cursor — Matplotlib 3.10.8 documentation
https://matplotlib.org/stable/gallery/widgets/mouse_cursor.html#sphx-glr-download-gallery-widgets-mouse-cursor-py
https://matplotlib.org/stable/_downloads/ab3f838084c7ddafe92dade4d05a6f67/mouse_cursor.py
mouse_cursor.py
widgets
ok
1
null
""" =========== Multicursor =========== Showing a cursor on multiple plots simultaneously. This example generates three Axes split over two different figures. On hovering the cursor over data in one subplot, the values of that datapoint are shown in all Axes. """ import matplotlib.pyplot as plt import numpy as np from matplotlib.widgets import MultiCursor t = np.arange(0.0, 2.0, 0.01) s1 = np.sin(2*np.pi*t) s2 = np.sin(3*np.pi*t) s3 = np.sin(4*np.pi*t) fig, (ax1, ax2) = plt.subplots(2, sharex=True) ax1.plot(t, s1) ax2.plot(t, s2) fig, ax3 = plt.subplots() ax3.plot(t, s3) multi = MultiCursor(None, (ax1, ax2, ax3), color='r', lw=1) plt.show() # %% # # .. admonition:: References # # The use of the following functions, methods, classes and modules is shown # in this example: # # - `matplotlib.widgets.MultiCursor`
stable__gallery__widgets__multicursor
0
figure_000.png
Multicursor — Matplotlib 3.10.8 documentation
https://matplotlib.org/stable/gallery/widgets/multicursor.html#sphx-glr-download-gallery-widgets-multicursor-py
https://matplotlib.org/stable/_downloads/515d3050c92b37baf0ab9a6a1511df37/multicursor.py
multicursor.py
widgets
ok
2
null
""" =========== Multicursor =========== Showing a cursor on multiple plots simultaneously. This example generates three Axes split over two different figures. On hovering the cursor over data in one subplot, the values of that datapoint are shown in all Axes. """ import matplotlib.pyplot as plt import numpy as np from matplotlib.widgets import MultiCursor t = np.arange(0.0, 2.0, 0.01) s1 = np.sin(2*np.pi*t) s2 = np.sin(3*np.pi*t) s3 = np.sin(4*np.pi*t) fig, (ax1, ax2) = plt.subplots(2, sharex=True) ax1.plot(t, s1) ax2.plot(t, s2) fig, ax3 = plt.subplots() ax3.plot(t, s3) multi = MultiCursor(None, (ax1, ax2, ax3), color='r', lw=1) plt.show() # %% # # .. admonition:: References # # The use of the following functions, methods, classes and modules is shown # in this example: # # - `matplotlib.widgets.MultiCursor`
stable__gallery__widgets__multicursor
1
figure_001.png
Multicursor — Matplotlib 3.10.8 documentation
https://matplotlib.org/stable/gallery/widgets/multicursor.html#sphx-glr-download-gallery-widgets-multicursor-py
https://matplotlib.org/stable/_downloads/515d3050c92b37baf0ab9a6a1511df37/multicursor.py
multicursor.py
widgets
ok
2
null
""" ======================================================= Select indices from a collection using polygon selector ======================================================= Shows how one can select indices of a polygon interactively. """ import numpy as np from matplotlib.path import Path from matplotlib.widgets import PolygonSelector class SelectFromCollection: """ Select indices from a matplotlib collection using `PolygonSelector`. Selected indices are saved in the `ind` attribute. This tool fades out the points that are not part of the selection (i.e., reduces their alpha values). If your collection has alpha < 1, this tool will permanently alter the alpha values. Note that this tool selects collection objects based on their *origins* (i.e., `offsets`). Parameters ---------- ax : `~matplotlib.axes.Axes` Axes to interact with. collection : `matplotlib.collections.Collection` subclass Collection you want to select from. alpha_other : 0 <= float <= 1 To highlight a selection, this tool sets all selected points to an alpha value of 1 and non-selected points to *alpha_other*. """ def __init__(self, ax, collection, alpha_other=0.3): self.canvas = ax.figure.canvas self.collection = collection self.alpha_other = alpha_other self.xys = collection.get_offsets() self.Npts = len(self.xys) # Ensure that we have separate colors for each object self.fc = collection.get_facecolors() if len(self.fc) == 0: raise ValueError('Collection must have a facecolor') elif len(self.fc) == 1: self.fc = np.tile(self.fc, (self.Npts, 1)) self.poly = PolygonSelector(ax, self.onselect, draw_bounding_box=True) self.ind = [] def onselect(self, verts): path = Path(verts) self.ind = np.nonzero(path.contains_points(self.xys))[0] self.fc[:, -1] = self.alpha_other self.fc[self.ind, -1] = 1 self.collection.set_facecolors(self.fc) self.canvas.draw_idle() def disconnect(self): self.poly.disconnect_events() self.fc[:, -1] = 1 self.collection.set_facecolors(self.fc) self.canvas.draw_idle() if __name__ == '__main__': import matplotlib.pyplot as plt fig, ax = plt.subplots() grid_size = 5 grid_x = np.tile(np.arange(grid_size), grid_size) grid_y = np.repeat(np.arange(grid_size), grid_size) pts = ax.scatter(grid_x, grid_y) selector = SelectFromCollection(ax, pts) print("Select points in the figure by enclosing them within a polygon.") print("Press the 'esc' key to start a new polygon.") print("Try holding the 'shift' key to move all of the vertices.") print("Try holding the 'ctrl' key to move a single vertex.") plt.show() selector.disconnect() # After figure is closed print the coordinates of the selected points print('\nSelected points:') print(selector.xys[selector.ind]) # %% # # .. admonition:: References # # The use of the following functions, methods, classes and modules is shown # in this example: # # - `matplotlib.widgets.PolygonSelector` # - `matplotlib.path.Path`
stable__gallery__widgets__polygon_selector_demo
0
figure_000.png
Select indices from a collection using polygon selector — Matplotlib 3.10.8 documentation
https://matplotlib.org/stable/gallery/widgets/polygon_selector_demo.html#sphx-glr-download-gallery-widgets-polygon-selector-demo-py
https://matplotlib.org/stable/_downloads/e01448737f71ce88ac3f2177a351c1de/polygon_selector_demo.py
polygon_selector_demo.py
widgets
ok
1
null
""" ================ Polygon Selector ================ Shows how to create a polygon programmatically or interactively """ import matplotlib.pyplot as plt from matplotlib.widgets import PolygonSelector # %% # # To create the polygon programmatically fig, ax = plt.subplots() fig.show() selector = PolygonSelector(ax, lambda *args: None) # Add three vertices selector.verts = [(0.1, 0.4), (0.5, 0.9), (0.3, 0.2)] # %% # # To create the polygon interactively fig2, ax2 = plt.subplots() fig2.show() selector2 = PolygonSelector(ax2, lambda *args: None) print("Click on the figure to create a polygon.") print("Press the 'esc' key to start a new polygon.") print("Try holding the 'shift' key to move all of the vertices.") print("Try holding the 'ctrl' key to move a single vertex.") # %% # .. tags:: # # component: axes, # styling: position, # plot-type: line, # level: intermediate, # domain: cartography, # domain: geometry, # domain: statistics, # # .. admonition:: References # # The use of the following functions, methods, classes and modules is shown # in this example: # # - `matplotlib.widgets.PolygonSelector`
stable__gallery__widgets__polygon_selector_simple
0
figure_000.png
Polygon Selector — Matplotlib 3.10.8 documentation
https://matplotlib.org/stable/gallery/widgets/polygon_selector_simple.html#sphx-glr-download-gallery-widgets-polygon-selector-simple-py
https://matplotlib.org/stable/_downloads/82a3b4570f59acc5a372cb7be136c952/polygon_selector_simple.py
polygon_selector_simple.py
widgets
ok
2
null
""" ================ Polygon Selector ================ Shows how to create a polygon programmatically or interactively """ import matplotlib.pyplot as plt from matplotlib.widgets import PolygonSelector # %% # # To create the polygon programmatically fig, ax = plt.subplots() fig.show() selector = PolygonSelector(ax, lambda *args: None) # Add three vertices selector.verts = [(0.1, 0.4), (0.5, 0.9), (0.3, 0.2)] # %% # # To create the polygon interactively fig2, ax2 = plt.subplots() fig2.show() selector2 = PolygonSelector(ax2, lambda *args: None) print("Click on the figure to create a polygon.") print("Press the 'esc' key to start a new polygon.") print("Try holding the 'shift' key to move all of the vertices.") print("Try holding the 'ctrl' key to move a single vertex.") # %% # .. tags:: # # component: axes, # styling: position, # plot-type: line, # level: intermediate, # domain: cartography, # domain: geometry, # domain: statistics, # # .. admonition:: References # # The use of the following functions, methods, classes and modules is shown # in this example: # # - `matplotlib.widgets.PolygonSelector`
stable__gallery__widgets__polygon_selector_simple
1
figure_001.png
Polygon Selector — Matplotlib 3.10.8 documentation
https://matplotlib.org/stable/gallery/widgets/polygon_selector_simple.html#sphx-glr-download-gallery-widgets-polygon-selector-simple-py
https://matplotlib.org/stable/_downloads/82a3b4570f59acc5a372cb7be136c952/polygon_selector_simple.py
polygon_selector_simple.py
widgets
ok
2
null
""" ============= Radio Buttons ============= Using radio buttons to choose properties of your plot. Radio buttons let you choose between multiple options in a visualization. In this case, the buttons let the user choose one of the three different sine waves to be shown in the plot. Radio buttons may be styled using the *label_props* and *radio_props* parameters, which each take a dictionary with keys of artist property names and values of lists of settings with length matching the number of buttons. """ import matplotlib.pyplot as plt import numpy as np from matplotlib.widgets import RadioButtons t = np.arange(0.0, 2.0, 0.01) s0 = np.sin(2*np.pi*t) s1 = np.sin(4*np.pi*t) s2 = np.sin(8*np.pi*t) fig, ax = plt.subplot_mosaic( [ ['main', 'freq'], ['main', 'color'], ['main', 'linestyle'], ], width_ratios=[5, 1], layout='constrained', ) l, = ax['main'].plot(t, s0, lw=2, color='red') radio_background = 'lightgoldenrodyellow' ax['freq'].set_facecolor(radio_background) radio = RadioButtons(ax['freq'], ('1 Hz', '2 Hz', '4 Hz'), label_props={'color': 'cmy', 'fontsize': [12, 14, 16]}, radio_props={'s': [16, 32, 64]}) def hzfunc(label): hzdict = {'1 Hz': s0, '2 Hz': s1, '4 Hz': s2} ydata = hzdict[label] l.set_ydata(ydata) fig.canvas.draw() radio.on_clicked(hzfunc) ax['color'].set_facecolor(radio_background) radio2 = RadioButtons( ax['color'], ('red', 'blue', 'green'), label_props={'color': ['red', 'blue', 'green']}, radio_props={ 'facecolor': ['red', 'blue', 'green'], 'edgecolor': ['darkred', 'darkblue', 'darkgreen'], }) def colorfunc(label): l.set_color(label) fig.canvas.draw() radio2.on_clicked(colorfunc) ax['linestyle'].set_facecolor(radio_background) radio3 = RadioButtons(ax['linestyle'], ('-', '--', '-.', ':')) def stylefunc(label): l.set_linestyle(label) fig.canvas.draw() radio3.on_clicked(stylefunc) plt.show() # %% # # .. admonition:: References # # The use of the following functions, methods, classes and modules is shown # in this example: # # - `matplotlib.widgets.RadioButtons`
stable__gallery__widgets__radio_buttons
0
figure_000.png
Radio Buttons — Matplotlib 3.10.8 documentation
https://matplotlib.org/stable/gallery/widgets/radio_buttons.html#sphx-glr-download-gallery-widgets-radio-buttons-py
https://matplotlib.org/stable/_downloads/51785ae53b1786fb0ed5b01f90362232/radio_buttons.py
radio_buttons.py
widgets
ok
1
null
""" ================================= Image scaling using a RangeSlider ================================= Using the RangeSlider widget to control the thresholding of an image. The RangeSlider widget can be used similarly to the `.widgets.Slider` widget. The major difference is that RangeSlider's ``val`` attribute is a tuple of floats ``(lower val, upper val)`` rather than a single float. See :doc:`/gallery/widgets/slider_demo` for an example of using a ``Slider`` to control a single float. See :doc:`/gallery/widgets/slider_snap_demo` for an example of having the ``Slider`` snap to discrete values. """ import matplotlib.pyplot as plt import numpy as np from matplotlib.widgets import RangeSlider # generate a fake image np.random.seed(19680801) N = 128 img = np.random.randn(N, N) fig, axs = plt.subplots(1, 2, figsize=(10, 5)) fig.subplots_adjust(bottom=0.25) im = axs[0].imshow(img) axs[1].hist(img.flatten(), bins='auto') axs[1].set_title('Histogram of pixel intensities') # Create the RangeSlider slider_ax = fig.add_axes([0.20, 0.1, 0.60, 0.03]) slider = RangeSlider(slider_ax, "Threshold", img.min(), img.max()) # Create the Vertical lines on the histogram lower_limit_line = axs[1].axvline(slider.val[0], color='k') upper_limit_line = axs[1].axvline(slider.val[1], color='k') def update(val): # The val passed to a callback by the RangeSlider will # be a tuple of (min, max) # Update the image's colormap im.norm.vmin = val[0] im.norm.vmax = val[1] # Update the position of the vertical lines lower_limit_line.set_xdata([val[0], val[0]]) upper_limit_line.set_xdata([val[1], val[1]]) # Redraw the figure to ensure it updates fig.canvas.draw_idle() slider.on_changed(update) plt.show() # %% # # .. admonition:: References # # The use of the following functions, methods, classes and modules is shown # in this example: # # - `matplotlib.widgets.RangeSlider`
stable__gallery__widgets__range_slider
0
figure_000.png
Image scaling using a RangeSlider — Matplotlib 3.10.8 documentation
https://matplotlib.org/stable/gallery/widgets/range_slider.html#sphx-glr-download-gallery-widgets-range-slider-py
https://matplotlib.org/stable/_downloads/5d09fa7f28b450731d677f4d2e54e675/range_slider.py
range_slider.py
widgets
ok
1
null
""" =============================== Rectangle and ellipse selectors =============================== Click somewhere, move the mouse, and release the mouse button. `.RectangleSelector` and `.EllipseSelector` draw a rectangle or an ellipse from the initial click position to the current mouse position (within the same axes) until the button is released. A connected callback receives the click- and release-events. """ import matplotlib.pyplot as plt import numpy as np from matplotlib.widgets import EllipseSelector, RectangleSelector def select_callback(eclick, erelease): """ Callback for line selection. *eclick* and *erelease* are the press and release events. """ x1, y1 = eclick.xdata, eclick.ydata x2, y2 = erelease.xdata, erelease.ydata print(f"({x1:3.2f}, {y1:3.2f}) --> ({x2:3.2f}, {y2:3.2f})") print(f"The buttons you used were: {eclick.button} {erelease.button}") def toggle_selector(event): print('Key pressed.') if event.key == 't': for selector in selectors: name = type(selector).__name__ if selector.active: print(f'{name} deactivated.') selector.set_active(False) else: print(f'{name} activated.') selector.set_active(True) fig = plt.figure(layout='constrained') axs = fig.subplots(2) N = 100000 # If N is large one can see improvement by using blitting. x = np.linspace(0, 10, N) selectors = [] for ax, selector_class in zip(axs, [RectangleSelector, EllipseSelector]): ax.plot(x, np.sin(2*np.pi*x)) # plot something ax.set_title(f"Click and drag to draw a {selector_class.__name__}.") selectors.append(selector_class( ax, select_callback, useblit=True, button=[1, 3], # disable middle button minspanx=5, minspany=5, spancoords='pixels', interactive=True)) fig.canvas.mpl_connect('key_press_event', toggle_selector) axs[0].set_title("Press 't' to toggle the selectors on and off.\n" + axs[0].get_title()) plt.show() # %% # # .. admonition:: References # # The use of the following functions, methods, classes and modules is shown # in this example: # # - `matplotlib.widgets.RectangleSelector` # - `matplotlib.widgets.EllipseSelector`
stable__gallery__widgets__rectangle_selector
0
figure_000.png
Rectangle and ellipse selectors — Matplotlib 3.10.8 documentation
https://matplotlib.org/stable/gallery/widgets/rectangle_selector.html#sphx-glr-download-gallery-widgets-rectangle-selector-py
https://matplotlib.org/stable/_downloads/6fd8c57479cccb2b7f96c0257b4200d1/rectangle_selector.py
rectangle_selector.py
widgets
ok
1
null
""" ====== Slider ====== In this example, sliders are used to control the frequency and amplitude of a sine wave. See :doc:`/gallery/widgets/slider_snap_demo` for an example of having the ``Slider`` snap to discrete values. See :doc:`/gallery/widgets/range_slider` for an example of using a ``RangeSlider`` to define a range of values. """ import matplotlib.pyplot as plt import numpy as np from matplotlib.widgets import Button, Slider # The parametrized function to be plotted def f(t, amplitude, frequency): return amplitude * np.sin(2 * np.pi * frequency * t) t = np.linspace(0, 1, 1000) # Define initial parameters init_amplitude = 5 init_frequency = 3 # Create the figure and the line that we will manipulate fig, ax = plt.subplots() line, = ax.plot(t, f(t, init_amplitude, init_frequency), lw=2) ax.set_xlabel('Time [s]') # adjust the main plot to make room for the sliders fig.subplots_adjust(left=0.25, bottom=0.25) # Make a horizontal slider to control the frequency. axfreq = fig.add_axes([0.25, 0.1, 0.65, 0.03]) freq_slider = Slider( ax=axfreq, label='Frequency [Hz]', valmin=0.1, valmax=30, valinit=init_frequency, ) # Make a vertically oriented slider to control the amplitude axamp = fig.add_axes([0.1, 0.25, 0.0225, 0.63]) amp_slider = Slider( ax=axamp, label="Amplitude", valmin=0, valmax=10, valinit=init_amplitude, orientation="vertical" ) # The function to be called anytime a slider's value changes def update(val): line.set_ydata(f(t, amp_slider.val, freq_slider.val)) fig.canvas.draw_idle() # register the update function with each slider freq_slider.on_changed(update) amp_slider.on_changed(update) # Create a `matplotlib.widgets.Button` to reset the sliders to initial values. resetax = fig.add_axes([0.8, 0.025, 0.1, 0.04]) button = Button(resetax, 'Reset', hovercolor='0.975') def reset(event): freq_slider.reset() amp_slider.reset() button.on_clicked(reset) plt.show() # %% # # .. admonition:: References # # The use of the following functions, methods, classes and modules is shown # in this example: # # - `matplotlib.widgets.Button` # - `matplotlib.widgets.Slider`
stable__gallery__widgets__slider_demo
0
figure_000.png
Slider — Matplotlib 3.10.8 documentation
https://matplotlib.org/stable/gallery/widgets/slider_demo.html#sphx-glr-download-gallery-widgets-slider-demo-py
https://matplotlib.org/stable/_downloads/34827ebbd80a7be269c66280f4b258ee/slider_demo.py
slider_demo.py
widgets
ok
1
null
""" =============================== Snap sliders to discrete values =============================== You can snap slider values to discrete values using the ``valstep`` argument. In this example the Freq slider is constrained to be multiples of pi, and the Amp slider uses an array as the ``valstep`` argument to more densely sample the first part of its range. See :doc:`/gallery/widgets/slider_demo` for an example of using a ``Slider`` to control a single float. See :doc:`/gallery/widgets/range_slider` for an example of using a ``RangeSlider`` to define a range of values. """ import matplotlib.pyplot as plt import numpy as np from matplotlib.widgets import Button, Slider t = np.arange(0.0, 1.0, 0.001) a0 = 5 f0 = 3 s = a0 * np.sin(2 * np.pi * f0 * t) fig, ax = plt.subplots() fig.subplots_adjust(bottom=0.25) l, = ax.plot(t, s, lw=2) ax_freq = fig.add_axes([0.25, 0.1, 0.65, 0.03]) ax_amp = fig.add_axes([0.25, 0.15, 0.65, 0.03]) # define the values to use for snapping allowed_amplitudes = np.concatenate([np.linspace(.1, 5, 100), [6, 7, 8, 9]]) # create the sliders samp = Slider( ax_amp, "Amp", 0.1, 9.0, valinit=a0, valstep=allowed_amplitudes, color="green" ) sfreq = Slider( ax_freq, "Freq", 0, 10*np.pi, valinit=2*np.pi, valstep=np.pi, initcolor='none' # Remove the line marking the valinit position. ) def update(val): amp = samp.val freq = sfreq.val l.set_ydata(amp*np.sin(2*np.pi*freq*t)) fig.canvas.draw_idle() sfreq.on_changed(update) samp.on_changed(update) ax_reset = fig.add_axes([0.8, 0.025, 0.1, 0.04]) button = Button(ax_reset, 'Reset', hovercolor='0.975') def reset(event): sfreq.reset() samp.reset() button.on_clicked(reset) plt.show() # %% # # .. admonition:: References # # The use of the following functions, methods, classes and modules is shown # in this example: # # - `matplotlib.widgets.Slider` # - `matplotlib.widgets.Button`
stable__gallery__widgets__slider_snap_demo
0
figure_000.png
Snap sliders to discrete values — Matplotlib 3.10.8 documentation
https://matplotlib.org/stable/gallery/widgets/slider_snap_demo.html#sphx-glr-download-gallery-widgets-slider-snap-demo-py
https://matplotlib.org/stable/_downloads/68c95e07ab61a26521daa7870bba11fe/slider_snap_demo.py
slider_snap_demo.py
widgets
ok
1
null
""" ============= Span Selector ============= The `.SpanSelector` is a mouse widget that enables selecting a range on an axis. Here, an x-range can be selected on the upper axis; a detailed view of the selected range is then plotted on the lower axis. .. note:: If the SpanSelector object is garbage collected you will lose the interactivity. You must keep a hard reference to it to prevent this. """ import matplotlib.pyplot as plt import numpy as np from matplotlib.widgets import SpanSelector # Fixing random state for reproducibility np.random.seed(19680801) fig, (ax1, ax2) = plt.subplots(2, figsize=(8, 6)) x = np.arange(0.0, 5.0, 0.01) y = np.sin(2 * np.pi * x) + 0.5 * np.random.randn(len(x)) ax1.plot(x, y) ax1.set_ylim(-2, 2) ax1.set_title('Press left mouse button and drag ' 'to select a region in the top graph') line2, = ax2.plot([], []) def onselect(xmin, xmax): indmin, indmax = np.searchsorted(x, (xmin, xmax)) indmax = min(len(x) - 1, indmax) region_x = x[indmin:indmax] region_y = y[indmin:indmax] if len(region_x) >= 2: line2.set_data(region_x, region_y) ax2.set_xlim(region_x[0], region_x[-1]) ax2.set_ylim(region_y.min(), region_y.max()) fig.canvas.draw_idle() span = SpanSelector( ax1, onselect, "horizontal", useblit=True, props=dict(alpha=0.5, facecolor="tab:blue"), interactive=True, drag_from_anywhere=True ) # Set useblit=True on most backends for enhanced performance. plt.show() # %% # # .. admonition:: References # # The use of the following functions, methods, classes and modules is shown # in this example: # # - `matplotlib.widgets.SpanSelector`
stable__gallery__widgets__span_selector
0
figure_000.png
Span Selector — Matplotlib 3.10.8 documentation
https://matplotlib.org/stable/gallery/widgets/span_selector.html#sphx-glr-download-gallery-widgets-span-selector-py
https://matplotlib.org/stable/_downloads/b6df01615e62198a6e6b651c4b836b36/span_selector.py
span_selector.py
widgets
ok
1
null
""" ======= Textbox ======= The Textbox widget lets users interactively provide text input, including formulas. In this example, the plot is updated using the `.on_submit` method. This method triggers the execution of the *submit* function when the user presses enter in the textbox or leaves the textbox. Note: The `matplotlib.widgets.TextBox` widget is different from the following static elements: :ref:`annotations` and :doc:`/gallery/text_labels_and_annotations/placing_text_boxes`. """ import matplotlib.pyplot as plt import numpy as np from matplotlib.widgets import TextBox fig, ax = plt.subplots() fig.subplots_adjust(bottom=0.2) t = np.arange(-2.0, 2.0, 0.001) l, = ax.plot(t, np.zeros_like(t), lw=2) def submit(expression): """ Update the plotted function to the new math *expression*. *expression* is a string using "t" as its independent variable, e.g. "t ** 3". """ ydata = eval(expression, {'np': np}, {'t': t}) l.set_ydata(ydata) ax.relim() ax.autoscale_view() plt.draw() axbox = fig.add_axes([0.1, 0.05, 0.8, 0.075]) text_box = TextBox(axbox, "Evaluate", textalignment="center") text_box.on_submit(submit) text_box.set_val("t ** 2") # Trigger `submit` with the initial string. plt.show() # %% # # .. admonition:: References # # The use of the following functions, methods, classes and modules is shown # in this example: # # - `matplotlib.widgets.TextBox`
stable__gallery__widgets__textbox
0
figure_000.png
Textbox — Matplotlib 3.10.8 documentation
https://matplotlib.org/stable/gallery/widgets/textbox.html#textbox
https://matplotlib.org/stable/_downloads/9af1076c2fab3dbe816bfbf4cfe1b9f5/textbox.py
textbox.py
widgets
ok
1
null