The main aim of mplutils is to help in the daily work with matplotlib. The motivation to create the library is to help in some tasks that should be easier if you use them on a daily basis and to provide some information that sometimes is not easy to find/understand (at least for me).

The library is divided in diferent sections related with main topics of Matplotlib usage.

  • colors: Some tools to work with colors and to provide best practices.
  • text: Very simple tools to inspect text features.
  • figure: Transformations applied to a Figure instance.
  • axes: Transformations applied to an Axes instance.
  • charts: Some best practices for some chart types as well as some functions to create not so frequent charts.

In [1]:
%cd ..


H:\mplutils

In [2]:
import numpy as np
import matplotlib.pyplot as plt
import mplutils as mplu
%matplotlib inline

Text

Get the name of the available fonts in the system.

Here we only show the first ten options:


In [3]:
mplu.text.text_getinfo_availablesystemfonts()[0:10]


Out[3]:
['c:\\windows\\fonts\\trob.ttf',
 'C:\\Windows\\Fonts\\leelawad.ttf',
 'c:\\windows\\fonts\\ahronbd.ttf',
 'C:\\Windows\\Fonts\\consolaz.ttf',
 'C:\\Windows\\Fonts\\ebrimabd.ttf',
 'C:\\Windows\\Fonts\\ITCEDSCR.TTF',
 'C:\\Windows\\Fonts\\GOUDOSB.TTF',
 'C:\\Windows\\Fonts\\upcfb.ttf',
 'c:\\windows\\fonts\\forte.ttf',
 'C:\\Windows\\Fonts\\tahomabd.ttf']

Colors

Get the color aliases used by matplotlib.

In a console the result will be a string like this one:


In [4]:
print(mplu.colors.colors_mpl_cnames())


springgreen:#00FF7F
royalblue:#4169E1
lightyellow:#FFFFE0
indianred:#CD5C5C
mediumaquamarine:#66CDAA
lightgray:#D3D3D3
seagreen:#2E8B57
blue:#0000FF
tan:#D2B48C
darkblue:#00008B
forestgreen:#228B22
thistle:#D8BFD8
slateblue:#6A5ACD
darkkhaki:#BDB76B
chocolate:#D2691E
mistyrose:#FFE4E1
black:#000000
whitesmoke:#F5F5F5
deepskyblue:#00BFFF
aliceblue:#F0F8FF
midnightblue:#191970
bisque:#FFE4C4
linen:#FAF0E6
dodgerblue:#1E90FF
lightgrey:#D3D3D3
papayawhip:#FFEFD5
dimgrey:#696969
paleturquoise:#AFEEEE
powderblue:#B0E0E6
darkslategray:#2F4F4F
floralwhite:#FFFAF0
wheat:#F5DEB3
navajowhite:#FFDEAD
honeydew:#F0FFF0
darkslateblue:#483D8B
chartreuse:#7FFF00
darkorange:#FF8C00
yellowgreen:#9ACD32
orangered:#FF4500
darkorchid:#9932CC
lightskyblue:#87CEFA
mediumpurple:#9370DB
slategray:#708090
goldenrod:#DAA520
ghostwhite:#F8F8FF
olive:#808000
magenta:#FF00FF
saddlebrown:#8B4513
sandybrown:#FAA460
lightsalmon:#FFA07A
dimgray:#696969
oldlace:#FDF5E6
steelblue:#4682B4
palegreen:#98FB98
slategrey:#708090
aqua:#00FFFF
white:#FFFFFF
orange:#FFA500
darkred:#8B0000
darkgoldenrod:#B8860B
lightsage:#BCECAC
limegreen:#32CD32
lightgoldenrodyellow:#FAFAD2
khaki:#F0E68C
darksage:#598556
sienna:#A0522D
crimson:#DC143C
salmon:#FA8072
seashell:#FFF5EE
turquoise:#40E0D0
cyan:#00FFFF
cadetblue:#5F9EA0
lightcoral:#F08080
gray:#808080
lightsteelblue:#B0C4DE
indigo:#4B0082
mediumblue:#0000CD
beige:#F5F5DC
olivedrab:#6B8E23
lightgreen:#90EE90
ivory:#FFFFF0
green:#008000
lightslategrey:#778899
darkgray:#A9A9A9
darkseagreen:#8FBC8F
cornflowerblue:#6495ED
gold:#FFD700
peru:#CD853F
mediumvioletred:#C71585
blanchedalmond:#FFEBCD
burlywood:#DEB887
darkolivegreen:#556B2F
maroon:#800000
lightcyan:#E0FFFF
fuchsia:#FF00FF
mediumslateblue:#7B68EE
violet:#EE82EE
darkslategrey:#2F4F4F
hotpink:#FF69B4
red:#FF0000
rosybrown:#BC8F8F
darkturquoise:#00CED1
palegoldenrod:#EEE8AA
brown:#A52A2A
greenyellow:#ADFF2F
lavenderblush:#FFF0F5
darkgrey:#A9A9A9
skyblue:#87CEEB
aquamarine:#7FFFD4
mediumorchid:#BA55D3
darksalmon:#E9967A
lemonchiffon:#FFFACD
lightseagreen:#20B2AA
mediumseagreen:#3CB371
plum:#DDA0DD
azure:#F0FFFF
pink:#FFC0CB
moccasin:#FFE4B5
darkviolet:#9400D3
lavender:#E6E6FA
lightslategray:#778899
grey:#808080
lawngreen:#7CFC00
gainsboro:#DCDCDC
snow:#FFFAFA
lightblue:#ADD8E6
firebrick:#B22222
silver:#C0C0C0
lime:#00FF00
mediumspringgreen:#00FA9A
darkcyan:#008B8B
antiquewhite:#FAEBD7
darkgreen:#006400
sage:#87AE73
tomato:#FF6347
cornsilk:#FFF8DC
teal:#008080
blueviolet:#8A2BE2
mediumturquoise:#48D1CC
palevioletred:#DB7093
navy:#000080
purple:#800080
yellow:#FFFF00
darkmagenta:#8B008B
mintcream:#F5FFFA
coral:#FF7F50
deeppink:#FF1493
orchid:#DA70D6
lightpink:#FFB6C1
peachpuff:#FFDAB9

In a notebook you could use a richer display using it like:


In [5]:
mplu.colors.colors_mpl_cnames()


Out[5]:
springgreen #00FF7F
royalblue #4169E1
lightyellow #FFFFE0
indianred #CD5C5C
mediumaquamarine #66CDAA
lightgray #D3D3D3
seagreen #2E8B57
blue #0000FF
tan #D2B48C
darkblue #00008B
forestgreen #228B22
thistle #D8BFD8
slateblue #6A5ACD
darkkhaki #BDB76B
chocolate #D2691E
mistyrose #FFE4E1
black #000000
whitesmoke #F5F5F5
deepskyblue #00BFFF
aliceblue #F0F8FF
midnightblue #191970
bisque #FFE4C4
linen #FAF0E6
dodgerblue #1E90FF
lightgrey #D3D3D3
papayawhip #FFEFD5
dimgrey #696969
paleturquoise #AFEEEE
powderblue #B0E0E6
darkslategray #2F4F4F
floralwhite #FFFAF0
wheat #F5DEB3
navajowhite #FFDEAD
honeydew #F0FFF0
darkslateblue #483D8B
chartreuse #7FFF00
darkorange #FF8C00
yellowgreen #9ACD32
orangered #FF4500
darkorchid #9932CC
lightskyblue #87CEFA
mediumpurple #9370DB
slategray #708090
goldenrod #DAA520
ghostwhite #F8F8FF
olive #808000
magenta #FF00FF
saddlebrown #8B4513
sandybrown #FAA460
lightsalmon #FFA07A
dimgray #696969
oldlace #FDF5E6
steelblue #4682B4
palegreen #98FB98
slategrey #708090
aqua #00FFFF
white #FFFFFF
orange #FFA500
darkred #8B0000
darkgoldenrod #B8860B
lightsage #BCECAC
limegreen #32CD32
lightgoldenrodyellow #FAFAD2
khaki #F0E68C
darksage #598556
sienna #A0522D
crimson #DC143C
salmon #FA8072
seashell #FFF5EE
turquoise #40E0D0
cyan #00FFFF
cadetblue #5F9EA0
lightcoral #F08080
gray #808080
lightsteelblue #B0C4DE
indigo #4B0082
mediumblue #0000CD
beige #F5F5DC
olivedrab #6B8E23
lightgreen #90EE90
ivory #FFFFF0
green #008000
lightslategrey #778899
darkgray #A9A9A9
darkseagreen #8FBC8F
cornflowerblue #6495ED
gold #FFD700
peru #CD853F
mediumvioletred #C71585
blanchedalmond #FFEBCD
burlywood #DEB887
darkolivegreen #556B2F
maroon #800000
lightcyan #E0FFFF
fuchsia #FF00FF
mediumslateblue #7B68EE
violet #EE82EE
darkslategrey #2F4F4F
hotpink #FF69B4
red #FF0000
rosybrown #BC8F8F
darkturquoise #00CED1
palegoldenrod #EEE8AA
brown #A52A2A
greenyellow #ADFF2F
lavenderblush #FFF0F5
darkgrey #A9A9A9
skyblue #87CEEB
aquamarine #7FFFD4
mediumorchid #BA55D3
darksalmon #E9967A
lemonchiffon #FFFACD
lightseagreen #20B2AA
mediumseagreen #3CB371
plum #DDA0DD
azure #F0FFFF
pink #FFC0CB
moccasin #FFE4B5
darkviolet #9400D3
lavender #E6E6FA
lightslategray #778899
grey #808080
lawngreen #7CFC00
gainsboro #DCDCDC
snow #FFFAFA
lightblue #ADD8E6
firebrick #B22222
silver #C0C0C0
lime #00FF00
mediumspringgreen #00FA9A
darkcyan #008B8B
antiquewhite #FAEBD7
darkgreen #006400
sage #87AE73
tomato #FF6347
cornsilk #FFF8DC
teal #008080
blueviolet #8A2BE2
mediumturquoise #48D1CC
palevioletred #DB7093
navy #000080
purple #800080
yellow #FFFF00
darkmagenta #8B008B
mintcream #F5FFFA
coral #FF7F50
deeppink #FF1493
orchid #DA70D6
lightpink #FFB6C1
peachpuff #FFDAB9

If you only want colors related with a string you could use a string in the colors_mpl_cnames call and it will show only those aliases including the string used:


In [6]:
mplu.colors.colors_mpl_cnames('yellow')


Out[6]:
lightyellow #FFFFE0
greenyellow #ADFF2F
yellowgreen #9ACD32
lightgoldenrodyellow #FAFAD2
yellow #FFFF00

Check how a color image will be using a grayscale colormap.

Let's create a simple plot:


In [10]:
np.random.seed(1)
fig, ax = plt.subplots(figsize = (10, 2))
x, y = np.arange(-3, 7), np.random.rand(10)*5-5/2
ax.plot(x, y, color = 'cyan', lw = 20)
ax.plot(x, y - 1, color = 'lightblue', lw = 20)
ax.plot(x, y - 2, color = 'pink', lw = 20)


Out[10]:
[<matplotlib.lines.Line2D at 0x7dcd128>]

Now, let's check how the image would be in a grayscale colormap.

There are three possibilities to change from color to grayscale:


In [11]:
mplu.colors.colors_check_grayscale(fig, 'luminosity')



In [12]:
mplu.colors.colors_check_grayscale(fig, 'luma')


  • average: the grayscale is obtained using the average value between the Reg, Green and Blue channels.

In [13]:
mplu.colors.colors_check_grayscale(fig, 'average')


Warning: This functionality creates a hardcopy of the original image. If you want to save the grayscale image created on-the-fly you could use the filename keyword.

mplu.colors.colors_check_grayscale(fig, 'average', filename = 'sample.png') will create a file called sample.png on the actual folder.

Axes

Set better defaults for an Axes instance.

In order to provide some better defaults (this is very subjective) the function axes_set_better_defaults has been included. It does some very basic stuff:

  • Change figure facecolor to white.
  • Removes the grid.
  • Changes color and tick labels colors to a lighter gray.

For instance, the following figure:


In [11]:
fig, ax = plt.subplots(facecolor = 'lightgray')
ax.grid(True)
ax.plot([1,2,3])


Out[11]:
[<matplotlib.lines.Line2D at 0x7dd3f98>]

Would be like this one in case we apply axes_set_better_defaults to an Axes instance


In [12]:
fig, ax = plt.subplots(facecolor = 'lightgray')
ax.grid(True)
mplu.axes.axes_set_better_defaults(ax)
ax.plot([1,2,3])


Out[12]:
[<matplotlib.lines.Line2D at 0x7dadbe0>]

In [15]:
fig, (ax1, ax2) = plt.subplots(ncols = 2, figsize = (12, 6))
ax1.plot([1,2,3])
ax1.grid(True)
mplu.axes.axes_set_better_defaults(ax2)
ax2.plot([1,2,3])


Out[15]:
[<matplotlib.lines.Line2D at 0x90a55c0>]

Set better axis easily

The function axes_set_axis provides an easy way to manage the axis, their visibility, if the axis should show some pan,...


In [5]:
fig, (ax1, ax2, ax3) = plt.subplots(nrows = 3, figsize = (5, 15))

x = np.linspace(-np.pi, np.pi, 256, endpoint=True)
y = np.sin(x)

ax1.plot(x, y)
ax1.grid(True)
ax1.set_title('Default with grid')

mplu.axes.axes_set_axis(ax2, spines = ['bottom', 'left'], pan = 20)
ax2.plot(x, y)
ax2.set_title('Axis modified')

mplu.axes.axes_set_axis(ax3, spines = ['bottom', 'left'], pan = 20)
mplu.axes.axes_set_better_defaults(ax3, axes_color = '#666666')
ax3.plot(x, y)
ax3.set_title('Axis modified and better defaults', color = '#666666')
fig.tight_layout()


Set the center of the axis

The following code will center the origin of the axis on (0,0):


In [6]:
fig, ax = plt.subplots()

x = np.linspace(-np.pi, np.pi, 256, endpoint=True)
y = np.sin(x)

mplu.axes.axes_set_origin(ax)
ax.plot(x, y, lw = 2)


Out[6]:
[<matplotlib.lines.Line2D at 0x81a2a20>]

The previous example using also 'better defaults':


In [7]:
fig, ax = plt.subplots()

x = np.linspace(-np.pi, np.pi, 256, endpoint=True)
y = np.sin(x)

mplu.axes.axes_set_origin(ax)
mplu.axes.axes_set_better_defaults(ax)
ax.plot(x, y, lw = 2)


Out[7]:
[<matplotlib.lines.Line2D at 0x7d258d0>]

If you want the axis centered on a special location you can use the x, y keyword parameters:


In [8]:
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows = 2, ncols = 2, figsize = (10, 10))

x = np.linspace(-np.pi, np.pi, 256, endpoint=True)
y = np.sin(x)

mplu.axes.axes_set_origin(ax1)
ax1.plot(x, y, lw = 2)

mplu.axes.axes_set_origin(ax2, x = 0, y = x.min())
ax2.plot(x, y, lw = 2)

mplu.axes.axes_set_origin(ax3, x = y.max(), y = x.min())
ax3.plot(x, y, lw = 2)

mplu.axes.axes_set_origin(ax4, x = 0, y = x.max() + 1)
ax4.plot(x, y, lw = 2)

fig.tight_layout()


In some of the previous subplots the tick labels are not well located. You can use the xticks_position or the yticks_position to improve the layout.


In [12]:
fig, (ax3, ax4) = plt.subplots(nrows = 2, figsize = (10, 10))

x = np.linspace(-np.pi, np.pi, 256, endpoint=True)
y = np.sin(x)

mplu.axes.axes_set_origin(ax3, x = y.max(), y = -4, xticks_position = 'top')
ax3.plot(x, y, lw = 2)

mplu.axes.axes_set_origin(ax4, x = 0, y = 4, yticks_position = 'right')
ax4.plot(x, y, lw = 2)

fig.tight_layout()


Finally, if you don't want tick labels you could use xticks_visible and/or yticks_visible keyword parameters to remove ticks and ticklabels:


In [14]:
fig, ax = plt.subplots()

x = np.linspace(-np.pi, np.pi, 256, endpoint=True)
y = np.sin(x)

mplu.axes.axes_set_origin(ax, xticks_visible = False, yticks_visible = False)
mplu.axes.axes_set_better_defaults(ax)
ax.plot(x, y, lw = 2)
ax.set_ylim(-1.1, 1.1)


Out[14]:
(-1.1, 1.1)

Set axis aspect ratio

This is a dummy wrapper around Axes.set_aspect method. It is included just to remember I should apply an equal aspect ratio to axis scales in some situations.

For instance, in a linear relation sometimes it could be misleading to show the plot without aspect ratio. In this example one can infer the y variation in relation to x would be higher than it is:


In [3]:
np.random.seed(5)
x = np.random.rand(200) * 10
y = x / 4 + np.random.rand(200) - 0.5

fig, ax = plt.subplots()
ax.scatter(x, y)


Out[3]:
<matplotlib.collections.PathCollection at 0x767c908>

With equal axis aspect ratio:


In [3]:
np.random.seed(5)
x = np.random.rand(200) * 10
y = x / 4 + np.random.rand(200) - 0.5

fig, ax = plt.subplots()
mplu.axes.axes_set_aspect_ratio(ax, adjustable = 'datalim')
ax.scatter(x, y)


Out[3]:
<matplotlib.collections.PathCollection at 0x76eab00>

In [ ]: