Как поменять цвет графика в matplotlib

от admin

Plotting with Pride: colors in matplotlib

In this tutorial I explain some of the different ways you can use and manipulate colors in matplotlib.

Contents

Part 1: Named colors

You may already know that you can pass a color argument through commonly used plotting functions to set the color of your lines and points. Any common color will do, but there are actually more than a thousand named colors recognized by matplotlib.

There are four main groups of named colors in matplotlib: the default Tableau 10 Palette, 8 single character «base» colors, CSS colors, and all the colors from the xkcd survey. Their names and RGB tuples or HTML hex codes are available in dictionaries in the colors module:

Colors in the Tableau palette must be prefaced with «tab:»

Similarly, xkcd colors must be prefaced with «xkcd:»

All named colors are in ⎯������������⎯��������⎯������ . You can check if a color you are thinking of will be recognized by matplotlib by searching in there:

If you would like to peruse, just run this code:

You can also pass in RGB tuples and HTML hex codes. The former must be values between 0 and 1 (divide by 255 if you have a RBG tuple not in that interval), and the latter has to be a string.

If you search «color picker» in Google, the search engine will provide you an interactive tool with color sliders that provides RGB and HTML hex codes, of which there are 16 million different possible values.

To get the RGB tuple or HTML hex code of a color you know the name of, you can use the ����⎯������ and ����⎯������ functions:

You’re not limited to just lines and points — you can set the color of every aspect of your plot.

If there’s a color scheme you like, you can set it to your rcParams to keep the rest of your plots like that for the rest of your script or notebook. Here’s a figure style based on my alma mater:

Call ������.����������������.��������() to see everything you can change. Use rcParamsDefault to return to default:


Back to Top

Part 2: color cycle

By default, plot colors cycle through the 10 Tableau Palette colors. While you could set the color for each plot manually or in a loop, you can also set the color cycle to whatever you want by setting the property cycle attribute of your axis:

You can also add this color cycle to your rcParams to set this for all the plots in your notebook or script so you don’t have to do this every time:

You can also use the string «CN», where N is the position in the color cycle, to get that specific color:

matplotlib also has a built-in color cycle that is more accessible for those with color vision deficiency. You can use it by using the tableau-colorblind10 style sheet:

There is also seaborn-colorblind:

You can also set the linestyle property cycle to reduce the ambiguity of color:


Back to Top

Part 3: colormaps

You may also be familiar with setting colormaps, such as when using the imshow function. The default is called «viridis», but there are many built-in colormaps in matplotlib.

plt.colormaps() returns a list of all 164 built-in colormaps. This includes 82 colormaps and their reverse, which you can call by adding ‘_r’ after the name of your desired colormap. You can run the functions below to plot all of them up:

There are four main types of colormap: sequential colormaps increase incrementally in brightness or hue. This is useful for representing data in the which the order matters:

The perceptually uniform sequential colormaps (viridis, plasma, inferno, magma, and cividis) are generally the more accessible colormaps for those with color vision deficiency.

Diverging colormaps have two colors that also change in brightess and hue to meet at some neutral color in the middle. These are good to show change from some value of interest.

Cyclic colormaps come back to meet each other at each end, which is good for values that repeat or come back onto themselves.

Qualitative colormaps don’t have specific ordering and so are better suited for data sets in which the order doesn’t matter, or you can use them to choose a list of colors (which we’ll get to in a later section).

As I’ve shown above, colormaps don’t only have use in imshow: you can use the color to plot a third variable in scatter plots:

We can also use colormaps for some third variable in line plots. Using a line collection will make plotting several related line plots both easy and efficient:

If you’re plotting a continuous function, you can also add a nice gradient with pyplot.scatter:

However, if you have too few points, your data might not appear as one continuous line. Fortunately, you can also add changing color to line plots by using a line collection:

If there’s a range of values you don’t care about, or a range you want to focus on, you can use the vmin and vmax arguments:


Back to Top

Part 4: Colormap normalization

Real life data is complicated! What if our data isn’t linearly ordered?

We’re not learning much from the colors in the above plot. By default, colormaps map colors linearly from the minimum to maximum value. Luckily, we can map the colors in the colormap according to a Normalization class. For the plot above, let’s try normalizing it to a logarithmic scale using the LogNorm function in the colors module.

Much better! Similarly, you can normalize to a power law relationship with PowerNorm. PowerNorm takes the argument gamma, which is the power the color values will be mapped to.

Now, let’s consider again the example of random data around zero, except this time, presume that the distribution was not perfectly random and there was a skew in one direction. You’ll notice, especially if you use a diverging colormap, that zero is not our center color, and in fact pixels with a value of zero will appear light red in the plot below:

This might be misleading, and we might miss important information, such as how our data tends more positive than negative. We can set the center of our colormap using DivergingNorm, which takes the argument vcenter:

There, now it’s much more clear that the data leans more positive than negative and that white pixels are zero.

If you want your colors to be discrete, you can use BoundaryNorm. The argument boundaries is the boundary values between colors, and ncolors is the number of discrete colors to choose from in your chosen colormap. By default, the built in colormaps have 256 colors, but this doesn’t always have to be the case, as we’ll see in the next section.

Check out the documentation for a few other types of normalizations:

Part 5: Creating your own colormaps

Of course, you’re not limited to just the built-in colormaps as-is. You can create your own for countless possibilities. Let’s start by adjusting the built-in colormaps by getting a colormap instance with plt.get_cmap. If you would like the colors to be more discrete without setting a BoundaryNorm for each dataset, you can give an integer argument for the number of different color values:

Our new colormap is a function that we can pass floats between 0 and 1 through. This returns an array with dimensions (N points x 4). The first three columns are the RGB tuple values for each point, and the fourth is the alpha (opacity/intensity). Let’s create an array of colors that covers the full range of one of the built-in colormaps:

We can limit the range of colors as well by not starting and ending at 0 and 1:

The floats you pass through your colormap don’t have to be linearly increasing from 0 to 1. You could get the reverse colormap by passing an array of values starting at 1 and going to 0, or you could make your colors cyclic by using a sinusoid. As long as it’s normalized to be on [0,1], you can pass any array through the colormap.

We can also change the color array after its creation. Let’s change the alphas of our plot to match the derivative:

Or, let’s say I really like all but one color in a built in colormap. We can change that too:

You can create a completely new colormap from a list of colors:

If you want a gradient of colors interpolated between this list, you can create a Linear segmented colormap:

You can also use nodes to give greater weight to one color:

Now, it’s easy to get carried away when making your own colormap. When using colors to represent an important dimension of your data, it’s best to make things as clear as possible, which means the simpler the better. Usually, just two or three colors will get the job done. Consider a gradient between a light and dark color, or a light color between two darker colors if you want to highlight divergence from some baseline value:

If you want more than three or four colors, it’s best to remove any that are too similar and then sort the remaining by brightness. Take the colormap I created a couple of cells up. It’s a little confusing with both blue and magenta on either side of black. We’re seeing similar colors at different points on the scale, making it a little ambiguous.

What’s happening on the edges? Is the value going back up? Our eye is also naturally drawn to brighter colors. Is there something special about that white ring?

Let’s sort our colors by their brightness, for which I’ll use the «value» in HSV:

Much better. You can clearly see that the maximum is in the center and then decreases from there.

You don’t have to use colormaps in ways directly tied to your data. For example, you can add a gradient to your color cycle:

Alternatively, you could use one of the perceptually uniform colormaps I mentioned above to make a more accessible color cycle.

You could even add a gradient to your axes:

Here are some Pride inspired colormaps:

That’s all for now! If you have any questions or want to show me your colorful plots, reach out on twitter @ExoplanetPete. Happy plotting, and happy Pride!

Choosing Colormaps in Matplotlib#

Matplotlib has a number of built-in colormaps accessible via matplotlib.colormaps . There are also external libraries that have many extra colormaps, which can be viewed in the Third-party colormaps section of the Matplotlib documentation. Here we briefly discuss how to choose between the many options. For help on creating your own colormaps, see Creating Colormaps in Matplotlib .

Overview#

The idea behind choosing a good colormap is to find a good representation in 3D colorspace for your data set. The best colormap for any given data set depends on many things including:

Whether representing form or metric data ( [Ware] )

Your knowledge of the data set (e.g., is there a critical value from which the other values deviate?)

If there is an intuitive color scheme for the parameter you are plotting

If there is a standard in the field the audience may be expecting

For many applications, a perceptually uniform colormap is the best choice; i.e. a colormap in which equal steps in data are perceived as equal steps in the color space. Researchers have found that the human brain perceives changes in the lightness parameter as changes in the data much better than, for example, changes in hue. Therefore, colormaps which have monotonically increasing lightness through the colormap will be better interpreted by the viewer. Wonderful examples of perceptually uniform colormaps can be found in the Third-party colormaps section as well.

Color can be represented in 3D space in various ways. One way to represent color is using CIELAB. In CIELAB, color space is represented by lightness, \(L^*\) ; red-green, \(a^*\) ; and yellow-blue, \(b^*\) . The lightness parameter \(L^*\) can then be used to learn more about how the matplotlib colormaps will be perceived by viewers.

An excellent starting resource for learning about human perception of colormaps is from [IBM] .

Classes of colormaps#

Colormaps are often split into several categories based on their function (see, e.g., [Moreland] ):

Sequential: change in lightness and often saturation of color incrementally, often using a single hue; should be used for representing information that has ordering.

Diverging: change in lightness and possibly saturation of two different colors that meet in the middle at an unsaturated color; should be used when the information being plotted has a critical middle value, such as topography or when the data deviates around zero.

Cyclic: change in lightness of two different colors that meet in the middle and beginning/end at an unsaturated color; should be used for values that wrap around at the endpoints, such as phase angle, wind direction, or time of day.

Qualitative: often are miscellaneous colors; should be used to represent information which does not have ordering or relationships.

First, we’ll show the range of each colormap. Note that some seem to change more "quickly" than others.

Sequential#

For the Sequential plots, the lightness value increases monotonically through the colormaps. This is good. Some of the \(L^*\) values in the colormaps span from 0 to 100 (binary and the other grayscale), and others start around \(L^*=20\) . Those that have a smaller range of \(L^*\) will accordingly have a smaller perceptual range. Note also that the \(L^*\) function varies amongst the colormaps: some are approximately linear in \(L^*\) and others are more curved.

Perceptually Uniform Sequential colormaps

Sequential colormaps

Sequential2#

Many of the \(L^*\) values from the Sequential2 plots are monotonically increasing, but some (autumn, cool, spring, and winter) plateau or even go both up and down in \(L^*\) space. Others (afmhot, copper, gist_heat, and hot) have kinks in the \(L^*\) functions. Data that is being represented in a region of the colormap that is at a plateau or kink will lead to a perception of banding of the data in those values in the colormap (see [mycarta-banding] for an excellent example of this).

Sequential (2) colormaps

Diverging#

For the Diverging maps, we want to have monotonically increasing \(L^*\) values up to a maximum, which should be close to \(L^*=100\) , followed by monotonically decreasing \(L^*\) values. We are looking for approximately equal minimum \(L^*\) values at opposite ends of the colormap. By these measures, BrBG and RdBu are good options. coolwarm is a good option, but it doesn’t span a wide range of \(L^*\) values (see grayscale section below).

Diverging colormaps

Cyclic#

For Cyclic maps, we want to start and end on the same color, and meet a symmetric center point in the middle. \(L^*\) should change monotonically from start to middle, and inversely from middle to end. It should be symmetric on the increasing and decreasing side, and only differ in hue. At the ends and middle, \(L^*\) will reverse direction, which should be smoothed in \(L^*\) space to reduce artifacts. See [kovesi-colormaps] for more information on the design of cyclic maps.

The often-used HSV colormap is included in this set of colormaps, although it is not symmetric to a center point. Additionally, the \(L^*\) values vary widely throughout the colormap, making it a poor choice for representing data for viewers to see perceptually. See an extension on this idea at [mycarta-jet] .

Cyclic colormaps

Qualitative#

Qualitative colormaps are not aimed at being perceptual maps, but looking at the lightness parameter can verify that for us. The \(L^*\) values move all over the place throughout the colormap, and are clearly not monotonically increasing. These would not be good options for use as perceptual colormaps.

Qualitative colormaps

Miscellaneous#

Some of the miscellaneous colormaps have particular uses for which they have been created. For example, gist_earth, ocean, and terrain all seem to be created for plotting topography (green/brown) and water depths (blue) together. We would expect to see a divergence in these colormaps, then, but multiple kinks may not be ideal, such as in gist_earth and terrain. CMRmap was created to convert well to grayscale, though it does appear to have some small kinks in \(L^*\) . cubehelix was created to vary smoothly in both lightness and hue, but appears to have a small hump in the green hue area. turbo was created to display depth and disparity data.

Читать:
Как обновить драйвер процессора amd

The often-used jet colormap is included in this set of colormaps. We can see that the \(L^*\) values vary widely throughout the colormap, making it a poor choice for representing data for viewers to see perceptually. See an extension on this idea at [mycarta-jet] and [turbo] .

Miscellaneous colormaps

Lightness of Matplotlib colormaps#

Here we examine the lightness values of the matplotlib colormaps. Note that some documentation on the colormaps is available ( [list-colormaps] ).

  • colormaps
  • colormaps
  • colormaps
  • colormaps
  • colormaps
  • colormaps
  • colormaps

Grayscale conversion#

It is important to pay attention to conversion to grayscale for color plots, since they may be printed on black and white printers. If not carefully considered, your readers may end up with indecipherable plots because the grayscale changes unpredictably through the colormap.

Conversion to grayscale is done in many different ways [bw] . Some of the better ones use a linear combination of the rgb values of a pixel, but weighted according to how we perceive color intensity. A nonlinear method of conversion to grayscale is to use the \(L^*\) values of the pixels. In general, similar principles apply for this question as they do for presenting one’s information perceptually; that is, if a colormap is chosen that is monotonically increasing in \(L^*\) values, it will print in a reasonable manner to grayscale.

With this in mind, we see that the Sequential colormaps have reasonable representations in grayscale. Some of the Sequential2 colormaps have decent enough grayscale representations, though some (autumn, spring, summer, winter) have very little grayscale change. If a colormap like this was used in a plot and then the plot was printed to grayscale, a lot of the information may map to the same gray values. The Diverging colormaps mostly vary from darker gray on the outer edges to white in the middle. Some (PuOr and seismic) have noticeably darker gray on one side than the other and therefore are not very symmetric. coolwarm has little range of gray scale and would print to a more uniform plot, losing a lot of detail. Note that overlaid, labeled contours could help differentiate between one side of the colormap vs. the other since color cannot be used once a plot is printed to grayscale. Many of the Qualitative and Miscellaneous colormaps, such as Accent, hsv, jet and turbo, change from darker to lighter and back to darker grey throughout the colormap. This would make it impossible for a viewer to interpret the information in a plot once it is printed in grayscale.

  • Perceptually Uniform Sequential colormaps
  • Sequential colormaps
  • Sequential (2) colormaps
  • Diverging colormaps
  • Cyclic colormaps
  • Qualitative colormaps
  • Miscellaneous colormaps

Color vision deficiencies#

There is a lot of information available about color blindness (e.g., [colorblindness] ). Additionally, there are tools available to convert images to how they look for different types of color vision deficiencies.

The most common form of color vision deficiency involves differentiating between red and green. Thus, avoiding colormaps with both red and green will avoid many problems in general.

Specifying colors#

Matplotlib recognizes the following formats to specify a color.

RGB or RGBA (red, green, blue, alpha) tuple of float values in a closed interval [0, 1].

Case-insensitive hex RGB or RGBA string.

Case-insensitive RGB or RGBA string equivalent hex shorthand of duplicated characters.

String representation of float value in closed interval [0, 1] for grayscale values.

‘0.8’ as light gray

Single character shorthand notation for some basic colors.

The colors green, cyan, magenta, and yellow do not coincide with X11/CSS4 colors. Their particular shades were chosen for better visibility of colored lines against typical backgrounds.

Case-insensitive X11/CSS4 color name with no spaces.

Case-insensitive color name from xkcd color survey with ‘xkcd:’ prefix.

Case-insensitive Tableau Colors from ‘T10’ categorical palette.

This is the default color cycle.

"CN" color spec where ‘C’ precedes a number acting as an index into the default property cycle.

Matplotlib indexes color at draw time and defaults to black if cycle does not include color.

rcParams["axes.prop_cycle"] (default: cycler(‘color’, [‘#1f77b4’, ‘#ff7f0e’, ‘#2ca02c’, ‘#d62728’, ‘#9467bd’, ‘#8c564b’, ‘#e377c2’, ‘#7f7f7f’, ‘#bcbd22’, ‘#17becf’]) )

"Red", "Green", and "Blue" are the intensities of those colors. In combination, they represent the colorspace.

Transparency#

The alpha value of a color specifies its transparency, where 0 is fully transparent and 1 is fully opaque. When a color is semi-transparent, the background color will show through.

The alpha value determines the resulting color by blending the foreground color with the background color according to the formula

The following plot illustrates the effect of transparency.

alpha values

The orange rectangle is semi-transparent with alpha = 0.8. The top row of blue squares is drawn below and the bottom row of blue squares is drawn on top of the orange rectangle.

See also Zorder Demo to learn more on the drawing order.

"CN" color selection#

Matplotlib converts "CN" colors to RGBA when drawing Artists. The Styling with cycler section contains additional information about controlling colors and style properties.

  • style:
  • style:

The first color ‘C0’ is the title. Each plot uses the second and third colors of each style’s rcParams["axes.prop_cycle"] (default: cycler(‘color’, [‘#1f77b4’, ‘#ff7f0e’, ‘#2ca02c’, ‘#d62728’, ‘#9467bd’, ‘#8c564b’, ‘#e377c2’, ‘#7f7f7f’, ‘#bcbd22’, ‘#17becf’]) ). They are ‘C1’ and ‘C2’ , respectively.

Comparison between X11/CSS4 and xkcd colors#

95 out of the 148 X11/CSS4 color names also appear in the xkcd color survey. Almost all of them map to different color values in the X11/CSS4 and in the xkcd palette. Only ‘black’, ‘white’ and ‘cyan’ are identical.

For example, ‘blue’ maps to ‘#0000FF’ whereas ‘xkcd:blue’ maps to ‘#0343DF’ . Due to these name collisions, all xkcd colors have the ‘xkcd:’ prefix.

The visual below shows name collisions. Color names where color values agree are in bold.

colors

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

Способы задания цвета в Matplotlib

При рисовании графиков с помощью Matplotlib часто приходится задавать цвета: для кривых, геометрических фигур и стрелок, текста и т.д. В Matplotlib существует несколько способов для указания цветов. В зависимости от задачи, вы можете выбрать наиболее удобный в данном случае.

В этой статье мы будем использовать пример, в котором будут рисоваться два квадрата — один будет накрыт другим, поэтому нижний квадрат будет виден только в том случае, если цвет верхнего содержит альфа-канал, задающий степень прозрачности. Нижний квадрат для простоты всегда будет отображаться черным цветом.

Заодно будет отображаться строка, с помощью которой задается цвет в конкретном примере.

Начнем с самого часто используемого способа задания цвета — с помощью однобуквенной строки. Таких цветов сравнительно немного.

  • ‘b’ — синий цвет
  • ‘g’ — зеленый цвет
  • ‘r’ — красный цвет
  • ‘c’ — голубой цвет
  • ‘m’ — пурпурный цвет
  • ‘y’ — желтый цвет
  • ‘k’ — черный цвет
  • ‘w’ — белый цвет

Вот, как выглядит наш пример:

import matplotlib. lines
import matplotlib. patches
import matplotlib. path
import matplotlib. pyplot as plt

def drawRect ( color ) :
plt. xlim ( — 2 , 2 )
plt. ylim ( — 2 , 2 )
plt. grid ( )

axes = plt. gca ( )
axes. set_aspect ( "equal" )

# Создадим "нижний" прямоугольник
rect_back = matplotlib. patches . Rectangle ( ( — 1.0 , — 1.0 ) , 2 , 2 , color = ‘k’ )

# Создадим чуть больший прямоугольник поверх предыдущего
# С цветом этого прямоугольника мы будем экспериментировать
rect_front = matplotlib. patches . Rectangle ( ( — 1.5 , — 1.5 ) , 3 , 3 , color = color )

# Добавим прямоугольники на график
axes. add_patch ( rect_back )
axes. add_patch ( rect_front )

# Добавим заголовок с обозначением цвета
plt. title ( ‘color = <>‘ . format ( color ) )
plt. show ( )

if __name__ == "__main__" :
# Цвет большого прямоугольника на графике
color = ‘g’
drawRect ( color )

Внешний вид графика выглядит следующим образом:

В Matplotlib есть возможность задания цвета с помощью строки, описывающей цвет полным английским словом. Таких именованных цветов намного больше, чем однобуквенных именованных цветов. В документации есть хороший пример, генерирующий таблицу со всеми существующими именованными цветами. Ниже приведена картинка, полученная с помощью этого примера из документации.

А мы воспользуемся одним из этих цветов и изменим наш предыдущий пример:

import matplotlib. lines
import matplotlib. patches
import matplotlib. path
import matplotlib. pyplot as plt

def drawRect ( color ) :
plt. xlim ( — 2 , 2 )
plt. ylim ( — 2 , 2 )
plt. grid ( )

axes = plt. gca ( )
axes. set_aspect ( "equal" )

rect_back = matplotlib. patches . Rectangle ( ( — 1.0 , — 1.0 ) , 2 , 2 , color = ‘k’ )
rect_front = matplotlib. patches . Rectangle ( ( — 1.5 , — 1.5 ) , 3 , 3 , color = color )

axes. add_patch ( rect_back )
axes. add_patch ( rect_front )

plt. title ( ‘color = <>‘ . format ( color ) )
plt. show ( )

if __name__ == "__main__" :
# Полный список именованных цветов
# http://matplotlib.org/examples/color/named_colors.html
color = ‘goldenrod’
drawRect ( color )

Результат будет выглядеть следующим образом:

Также цвет можно задавать в формате RGB с использованием символа «#», как это принято в HTML и CSS, задавая компоненты цвета в 16-ричной системе счисления. Например:

import matplotlib. lines
import matplotlib. patches
import matplotlib. path
import matplotlib. pyplot as plt

def drawRect ( color ) :
plt. xlim ( — 2 , 2 )
plt. ylim ( — 2 , 2 )
plt. grid ( )

axes = plt. gca ( )
axes. set_aspect ( "equal" )

rect_back = matplotlib. patches . Rectangle ( ( — 1.0 , — 1.0 ) , 2 , 2 , color = ‘k’ )
rect_front = matplotlib. patches . Rectangle ( ( — 1.5 , — 1.5 ) , 3 , 3 , color = color )

axes. add_patch ( rect_back )
axes. add_patch ( rect_front )

plt. title ( ‘color = <>‘ . format ( color ) )
plt. show ( )

if __name__ == "__main__" :
# .
color = ‘#31D115’
drawRect ( color )

В результате получим:

Используя подобный этот формат («#RRGGBBAA») можно задать также альфа-канал (непрозрачность цвета). То есть, если в конце строки (16-ричные числа AA) стоит FF — это абсолютно не прозрачный цвет (как будто бы альфа-канал не указан), а если 00 — это полностью прозрачный цвет, и объект станет невидимым. Пример с альфа-каналом показан ниже. Наконец-то мы увидим нижний квадрат, который в предыдущих примерах был скрыт.

import matplotlib. lines
import matplotlib. patches
import matplotlib. path
import matplotlib. pyplot as plt

def drawRect ( color ) :
plt. xlim ( — 2 , 2 )
plt. ylim ( — 2 , 2 )
plt. grid ( )

axes = plt. gca ( )
axes. set_aspect ( "equal" )

rect_back = matplotlib. patches . Rectangle ( ( — 1.0 , — 1.0 ) , 2 , 2 , color = ‘k’ )
rect_front = matplotlib. patches . Rectangle ( ( — 1.5 , — 1.5 ) , 3 , 3 , color = color )

axes. add_patch ( rect_back )
axes. add_patch ( rect_front )

plt. title ( ‘color = <>‘ . format ( color ) )
plt. show ( )

if __name__ == "__main__" :
# .
color = ‘#33DD11AA’
drawRect ( color )

Так же, как и в HTML/CSS, цвет можно задавать в сокращенном виде (в формате «#RGB»), то есть вместо «#AAFF55» можно написать «#AF5». Это показано в следующем примере. В сокращенном виде значение альфа-канала задавать нельзя.

import matplotlib. lines
import matplotlib. patches
import matplotlib. path
import matplotlib. pyplot as plt

def drawRect ( color ) :
plt. xlim ( — 2 , 2 )
plt. ylim ( — 2 , 2 )
plt. grid ( )

axes = plt. gca ( )
axes. set_aspect ( "equal" )

rect_back = matplotlib. patches . Rectangle ( ( — 1.0 , — 1.0 ) , 2 , 2 , color = ‘k’ )
rect_front = matplotlib. patches . Rectangle ( ( — 1.5 , — 1.5 ) , 3 , 3 , color = color )

axes. add_patch ( rect_back )
axes. add_patch ( rect_front )

plt. title ( ‘color = <>‘ . format ( color ) )
plt. show ( )

if __name__ == "__main__" :
# .
color = ‘#AF5’
drawRect ( color )

На этот раз результат будет выглядеть следующим образом:

Еще один способ задания цвета — с помощью кортежа или списка из трех элементов, задающих компоненты R, G и B соответственно. Главная особенность такого способа задания цвета состоит в том, что компоненты цвета должны быть представлены числом с плавающей точкой в диапазоне от 0.0 до 1.0. Например:

import matplotlib. lines
import matplotlib. patches
import matplotlib. path
import matplotlib. pyplot as plt

def drawRect ( color ) :
plt. xlim ( — 2 , 2 )
plt. ylim ( — 2 , 2 )
plt. grid ( )

axes = plt. gca ( )
axes. set_aspect ( "equal" )

rect_back = matplotlib. patches . Rectangle ( ( — 1.0 , — 1.0 ) , 2 , 2 , color = ‘k’ )
rect_front = matplotlib. patches . Rectangle ( ( — 1.5 , — 1.5 ) , 3 , 3 , color = color )

axes. add_patch ( rect_back )
axes. add_patch ( rect_front )

plt. title ( ‘color = <>‘ . format ( color ) )
plt. show ( )

if __name__ == "__main__" :
# .
color = ( 0.5 , 0.2 , 0.3 )
drawRect ( color )

Результат будет выглядеть следующим образом:

Если мы к кортежу (или списку), описывающему цвет, добавим четвертый элемент, то он будет обозначать альфа-канал или непрозрачность. То есть, если четвертый элемент равен 1.0, то цвет будет полностью непрозрачным (как будто альфа-канал не задан), а если он равен 0.0, то объект будет полностью прозрачным (невидимым).

В следующем примере цвету добавлен альфа-канал со значением 0.8.

import matplotlib. lines
import matplotlib. patches
import matplotlib. path
import matplotlib. pyplot as plt

def drawRect ( color ) :
plt. xlim ( — 2 , 2 )
plt. ylim ( — 2 , 2 )
plt. grid ( )

axes = plt. gca ( )
axes. set_aspect ( "equal" )

rect_back = matplotlib. patches . Rectangle ( ( — 1.0 , — 1.0 ) , 2 , 2 , color = ‘k’ )
rect_front = matplotlib. patches . Rectangle ( ( — 1.5 , — 1.5 ) , 3 , 3 , color = color )

axes. add_patch ( rect_back )
axes. add_patch ( rect_front )

plt. title ( ‘color = <>‘ . format ( color ) )
plt. show ( )

if __name__ == "__main__" :
# .
color = ( 0.5 , 0.2 , 0.3 , 0.8 )
drawRect ( color )

Результат будет выглядеть следующим образом:

Особый случай задания цвета — это выбор серого цвета различной степени яркости. Как известно, серый цвет — это такой цвет, у которого компоненты R, G и B равны между собой, поэтому для задания серого цвета достаточно задать лишь одно число. В Matplotlib для этого в качестве цвета можно указать строку с числом с плавающей точкой в интервале от 0.0 (черный цвет) до 1.0 (белый цвет).

Следующий пример рисует серый квадрат:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import pylab
import matplotlib. patches
import matplotlib. lines
import matplotlib. path

def drawRect ( color ) :
pylab. xlim ( — 2 , 2 )
pylab. ylim ( — 2 , 2 )
pylab. grid ( )

axes = pylab. gca ( )
axes. set_aspect ( "equal" )

rect_back = matplotlib. patches . Rectangle ( ( — 0.5 , — 0.5 ) , 1 , 1 , color = ‘k’ )
rect_front = matplotlib. patches . Rectangle ( ( — 1 , — 1 ) , 2 , 2 , color = color )

axes. add_patch ( rect_back )
axes. add_patch ( rect_front )

pylab. text ( — 1.5 , 1.7 , u ‘color = <>‘ . format ( color ) )
pylab. show ( )

if __name__ == "__main__" :
color = ‘0.3’
drawRect ( color )

И в завершение рассмотрим еще один более экзотический способ. В Matplotlib можно выбирать цвет из таблицы цветов сайта xkcd. Для этого строка, описывающая цвет должна иметь формат ‘xkcd:имя_цвета’. Например, как показано далее:

import matplotlib. lines
import matplotlib. patches
import matplotlib. path
import matplotlib. pyplot as plt

def drawRect ( color ) :
plt. xlim ( — 2 , 2 )
plt. ylim ( — 2 , 2 )
plt. grid ( )

axes = plt. gca ( )
axes. set_aspect ( "equal" )

rect_back = matplotlib. patches . Rectangle ( ( — 1.0 , — 1.0 ) , 2 , 2 , color = ‘k’ )
rect_front = matplotlib. patches . Rectangle ( ( — 1.5 , — 1.5 ) , 3 , 3 , color = color )

axes. add_patch ( rect_back )
axes. add_patch ( rect_front )

plt. title ( ‘color = <>‘ . format ( color ) )
plt. show ( )

if __name__ == "__main__" :
# .
color = ‘xkcd:moss green’
drawRect ( color )

Результат будет выглядеть следующим образом:

Подводя итог всему вышесказанному, составим список способов задания цвета в Matplotlib:

  • С помощью однобуквенной строки (например, ‘g’).
  • С помощью словесного описания цвета (например, ‘goldenrod’).
  • С помощью словесного описания цвета из таблицы xkcd (например, ‘xkcd:moss green’)
  • С помощью указания компонент цвета в формате #RRGGBB (например, ‘#31D115’).
  • С помощью указания компонент цвета в формате #RGB (например, ‘#AF5’).
  • С помощью указания компонент цвета в виде кортежа или списка трех чисел в диапазоне 0.0 — 1.0 (например, (0.5, 0.2, 0.3)).
  • С помощью указания компонент цвета и альфа-канала в виде кортежа или списка четырех чисел в диапазоне 0.0 — 1.0 (например, (0.5, 0.2, 0.3, 0.8)).
  • Для задания серого цвета можно использовать строку с числом с плавающей точкой в диапазоне 0.0 — 1.0 (например, ‘0.3’).

Вы можете подписаться на новости сайта через RSS, Группу Вконтакте или Канал в Telegram.

Похожие статьи