Note
Click here
to download the full example code
Color formats#
Matplotlib recognizes the following formats to specify a color.
Format |
Example |
---|---|
RGB or RGBA (red, green, blue, alpha) |
|
Case-insensitive hex RGB or RGBA |
|
Case-insensitive RGB or RGBA string |
|
String representation of float value |
|
Single character shorthand notation Note The colors green, cyan, magenta, |
|
Case-insensitive X11/CSS4 color name |
|
Case-insensitive color name from |
|
Case-insensitive Tableau Colors from Note This is the default color |
|
«CN» color spec where Note Matplotlib indexes color |
|
|
«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
[RGB_{result} = RGB_{background} * (1 — alpha) + RGB_{foreground} * alpha]
The following plot illustrates the effect of transparency.
import matplotlib.pyplot as plt from matplotlib.patches import Rectangle import numpy as np fig, ax = plt.subplots(figsize=(6.5, 1.65), layout='constrained') ax.add_patch(Rectangle((-0.2, -0.35), 11.2, 0.7, color='C1', alpha=0.8)) for i, alpha in enumerate(np.linspace(0, 1, 11)): ax.add_patch(Rectangle((i, 0.05), 0.8, 0.6, alpha=alpha, zorder=0)) ax.text(i+0.4, 0.85, f"{alpha:.1f}", ha='center') ax.add_patch(Rectangle((i, -0.05), 0.8, -0.6, alpha=alpha, zorder=2)) ax.set_xlim(-0.2, 13) ax.set_ylim(-1, 1) ax.set_title('alpha values') ax.text(11.3, 0.6, 'zorder=1', va='center', color='C0') ax.text(11.3, 0, 'zorder=2nalpha=0.8', va='center', color='C1') ax.text(11.3, -0.6, 'zorder=3', va='center', color='C0') ax.axis('off')
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.
import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl th = np.linspace(0, 2*np.pi, 128) def demo(sty): mpl.style.use(sty) fig, ax = plt.subplots(figsize=(3, 3)) ax.set_title('style: {!r}'.format(sty), color='C0') ax.plot(th, np.cos(th), 'C1', label='C1') ax.plot(th, np.sin(th), 'C2', label='C2') ax.legend() demo('default') demo('seaborn-v0_8')
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#
The xkcd colors come from a user survey conducted by the webcomic xkcd.
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.
import matplotlib.colors as mcolors import matplotlib.patches as mpatch overlap = {name for name in mcolors.CSS4_COLORS if f'xkcd:{name}' in mcolors.XKCD_COLORS} fig = plt.figure(figsize=[9, 5]) ax = fig.add_axes([0, 0, 1, 1]) n_groups = 3 n_rows = len(overlap) // n_groups + 1 for j, color_name in enumerate(sorted(overlap)): css4 = mcolors.CSS4_COLORS[color_name] xkcd = mcolors.XKCD_COLORS[f'xkcd:{color_name}'].upper() # Pick text colour based on perceived luminance. rgba = mcolors.to_rgba_array([css4, xkcd]) luma = 0.299 * rgba[:, 0] + 0.587 * rgba[:, 1] + 0.114 * rgba[:, 2] css4_text_color = 'k' if luma[0] > 0.5 else 'w' xkcd_text_color = 'k' if luma[1] > 0.5 else 'w' col_shift = (j // n_rows) * 3 y_pos = j % n_rows text_args = dict(fontsize=10, weight='bold' if css4 == xkcd else None) ax.add_patch(mpatch.Rectangle((0 + col_shift, y_pos), 1, 1, color=css4)) ax.add_patch(mpatch.Rectangle((1 + col_shift, y_pos), 1, 1, color=xkcd)) ax.text(0.5 + col_shift, y_pos + .7, css4, color=css4_text_color, ha='center', **text_args) ax.text(1.5 + col_shift, y_pos + .7, xkcd, color=xkcd_text_color, ha='center', **text_args) ax.text(2 + col_shift, y_pos + .7, f' {color_name}', **text_args) for g in range(n_groups): ax.hlines(range(n_rows), 3*g, 3*g + 2.8, color='0.7', linewidth=1) ax.text(0.5 + 3*g, -0.3, 'X11/CSS4', ha='center') ax.text(1.5 + 3*g, -0.3, 'xkcd', ha='center') ax.set_xlim(0, 3 * n_groups) ax.set_ylim(n_rows, -1) ax.axis('off') plt.show()
Total running time of the script: ( 0 minutes 1.611 seconds)
Gallery generated by Sphinx-Gallery
Note
Click here
to download the full example code
An introduction to the pyplot interface. Please also see
Quick start guide for an overview of how Matplotlib
works and Matplotlib Application Interfaces (APIs) for an explanation of the trade-offs between the
supported user APIs.
Intro to pyplot#
matplotlib.pyplot
is a collection of functions that make matplotlib
work like MATLAB. Each pyplot
function makes some change to a figure:
e.g., creates a figure, creates a plotting area in a figure, plots some lines
in a plotting area, decorates the plot with labels, etc.
In matplotlib.pyplot
various states are preserved
across function calls, so that it keeps track of things like
the current figure and plotting area, and the plotting
functions are directed to the current axes (please note that «axes» here
and in most places in the documentation refers to the axes
part of a figure
and not the strict mathematical term for more than one axis).
Note
the implicit pyplot API is generally less verbose but also not as flexible as the
explicit API. Most of the function calls you see here can also be called
as methods from an Axes
object. We recommend browsing the tutorials
and examples to see how this works. See Matplotlib Application Interfaces (APIs) for an
explanation of the trade off of the supported user APIs.
Generating visualizations with pyplot is very quick:
You may be wondering why the x-axis ranges from 0-3 and the y-axis
from 1-4. If you provide a single list or array to
plot
, matplotlib assumes it is a
sequence of y values, and automatically generates the x values for
you. Since python ranges start with 0, the default x vector has the
same length as y but starts with 0. Hence the x data are
[0, 1, 2, 3]
.
plot
is a versatile function, and will take an arbitrary number of
arguments. For example, to plot x versus y, you can write:
Formatting the style of your plot#
For every x, y pair of arguments, there is an optional third argument
which is the format string that indicates the color and line type of
the plot. The letters and symbols of the format string are from
MATLAB, and you concatenate a color string with a line style string.
The default format string is ‘b-‘, which is a solid blue line. For
example, to plot the above with red circles, you would issue
plt.plot([1, 2, 3, 4], [1, 4, 9, 16], 'ro') plt.axis([0, 6, 0, 20]) plt.show()
See the plot
documentation for a complete
list of line styles and format strings. The
axis
function in the example above takes a
list of [xmin, xmax, ymin, ymax]
and specifies the viewport of the
axes.
If matplotlib were limited to working with lists, it would be fairly
useless for numeric processing. Generally, you will use numpy arrays. In fact, all sequences are
converted to numpy arrays internally. The example below illustrates
plotting several lines with different format styles in one function call
using arrays.
import numpy as np # evenly sampled time at 200ms intervals t = np.arange(0., 5., 0.2) # red dashes, blue squares and green triangles plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^') plt.show()
Plotting with keyword strings#
There are some instances where you have data in a format that lets you
access particular variables with strings. For example, with
numpy.recarray
or pandas.DataFrame
.
Matplotlib allows you provide such an object with
the data
keyword argument. If provided, then you may generate plots with
the strings corresponding to these variables.
Plotting with categorical variables#
It is also possible to create a plot using categorical variables.
Matplotlib allows you to pass categorical variables directly to
many plotting functions. For example:
Controlling line properties#
Lines have many attributes that you can set: linewidth, dash style,
antialiased, etc; see matplotlib.lines.Line2D
. There are
several ways to set line properties
-
Use keyword arguments:
-
Use the setter methods of a
Line2D
instance.plot
returns a list
ofLine2D
objects; e.g.,line1, line2 = plot(x1, y1, x2, y2)
. In the code
below we will suppose that we have only
one line so that the list returned is of length 1. We use tuple unpacking with
line,
to get the first element of that list: -
Use
setp
. The example below
uses a MATLAB-style function to set multiple properties
on a list of lines.setp
works transparently with a list of objects
or a single object. You can either use python keyword arguments or
MATLAB-style string/value pairs:lines = plt.plot(x1, y1, x2, y2) # use keyword arguments plt.setp(lines, color='r', linewidth=2.0) # or MATLAB style string value pairs plt.setp(lines, 'color', 'r', 'linewidth', 2.0)
Here are the available Line2D
properties.
Property |
Value Type |
---|---|
alpha |
float |
animated |
[True | False] |
antialiased or aa |
[True | False] |
clip_box |
a matplotlib.transform.Bbox instance |
clip_on |
[True | False] |
clip_path |
a Path instance and a Transform instance, a Patch |
color or c |
any matplotlib color |
contains |
the hit testing function |
dash_capstyle |
[ |
dash_joinstyle |
[ |
dashes |
sequence of on/off ink in points |
data |
(np.array xdata, np.array ydata) |
figure |
a matplotlib.figure.Figure instance |
label |
any string |
linestyle or ls |
[ |
linewidth or lw |
float value in points |
marker |
[ |
markeredgecolor or mec |
any matplotlib color |
markeredgewidth or mew |
float value in points |
markerfacecolor or mfc |
any matplotlib color |
markersize or ms |
float |
markevery |
[ None | integer | (startind, stride) ] |
picker |
used in interactive line selection |
pickradius |
the line pick selection radius |
solid_capstyle |
[ |
solid_joinstyle |
[ |
transform |
a matplotlib.transforms.Transform instance |
visible |
[True | False] |
xdata |
np.array |
ydata |
np.array |
zorder |
any number |
To get a list of settable line properties, call the
setp
function with a line or lines as argument
In [69]: lines = plt.plot([1, 2, 3]) In [70]: plt.setp(lines) alpha: float animated: [True | False] antialiased or aa: [True | False] ...snip
Working with multiple figures and axes#
MATLAB, and pyplot
, have the concept of the current figure
and the current axes. All plotting functions apply to the current
axes. The function gca
returns the current axes (a
matplotlib.axes.Axes
instance), and gcf
returns the current
figure (a matplotlib.figure.Figure
instance). Normally, you don’t have to
worry about this, because it is all taken care of behind the scenes. Below
is a script to create two subplots.
def f(t): return np.exp(-t) * np.cos(2*np.pi*t) t1 = np.arange(0.0, 5.0, 0.1) t2 = np.arange(0.0, 5.0, 0.02) plt.figure() plt.subplot(211) plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k') plt.subplot(212) plt.plot(t2, np.cos(2*np.pi*t2), 'r--') plt.show()
The figure
call here is optional because a figure will be created
if none exists, just as an Axes will be created (equivalent to an explicit
subplot()
call) if none exists.
The subplot
call specifies numrows,
where
numcols, plot_numberplot_number
ranges from 1 to
numrows*numcols
. The commas in the subplot
call are
optional if numrows*numcols<10
. So subplot(211)
is identical
to subplot(2, 1, 1)
.
You can create an arbitrary number of subplots
and axes. If you want to place an Axes manually, i.e., not on a
rectangular grid, use axes
,
which allows you to specify the location as axes([left, bottom,
where all values are in fractional (0 to 1)
width, height])
coordinates. See Axes Demo for an example of
placing axes manually and Multiple subplots for an
example with lots of subplots.
You can create multiple figures by using multiple
figure
calls with an increasing figure
number. Of course, each figure can contain as many axes and subplots
as your heart desires:
import matplotlib.pyplot as plt plt.figure(1) # the first figure plt.subplot(211) # the first subplot in the first figure plt.plot([1, 2, 3]) plt.subplot(212) # the second subplot in the first figure plt.plot([4, 5, 6]) plt.figure(2) # a second figure plt.plot([4, 5, 6]) # creates a subplot() by default plt.figure(1) # first figure current; # subplot(212) still current plt.subplot(211) # make subplot(211) in the first figure # current plt.title('Easy as 1, 2, 3') # subplot 211 title
You can clear the current figure with clf
and the current axes with cla
. If you find
it annoying that states (specifically the current image, figure and axes)
are being maintained for you behind the scenes, don’t despair: this is just a thin
stateful wrapper around an object-oriented API, which you can use
instead (see Artist tutorial)
If you are making lots of figures, you need to be aware of one
more thing: the memory required for a figure is not completely
released until the figure is explicitly closed with
close
. Deleting all references to the
figure, and/or using the window manager to kill the window in which
the figure appears on the screen, is not enough, because pyplot
maintains internal references until close
is called.
Working with text#
text
can be used to add text in an arbitrary location, and
xlabel
, ylabel
and title
are used to add
text in the indicated locations (see Text in Matplotlib Plots for a
more detailed example)
mu, sigma = 100, 15 x = mu + sigma * np.random.randn(10000) # the histogram of the data n, bins, patches = plt.hist(x, 50, density=True, facecolor='g', alpha=0.75) plt.xlabel('Smarts') plt.ylabel('Probability') plt.title('Histogram of IQ') plt.text(60, .025, r'$mu=100, sigma=15$') plt.axis([40, 160, 0, 0.03]) plt.grid(True) plt.show()
All of the text
functions return a matplotlib.text.Text
instance. Just as with lines above, you can customize the properties by
passing keyword arguments into the text functions or using setp
:
These properties are covered in more detail in Text properties and layout.
Using mathematical expressions in text#
matplotlib accepts TeX equation expressions in any text expression.
For example to write the expression (sigma_i=15) in the title,
you can write a TeX expression surrounded by dollar signs:
The r
preceding the title string is important — it signifies
that the string is a raw string and not to treat backslashes as
python escapes. matplotlib has a built-in TeX expression parser and
layout engine, and ships its own math fonts — for details see
Writing mathematical expressions. Thus you can use mathematical text across platforms
without requiring a TeX installation. For those who have LaTeX and
dvipng installed, you can also use LaTeX to format your text and
incorporate the output directly into your display figures or saved
postscript — see Text rendering with LaTeX.
Annotating text#
The uses of the basic text
function above
place text at an arbitrary position on the Axes. A common use for
text is to annotate some feature of the plot, and the
annotate
method provides helper
functionality to make annotations easy. In an annotation, there are
two points to consider: the location being annotated represented by
the argument xy
and the location of the text xytext
. Both of
these arguments are (x, y)
tuples.
ax = plt.subplot() t = np.arange(0.0, 5.0, 0.01) s = np.cos(2*np.pi*t) line, = plt.plot(t, s, lw=2) plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5), arrowprops=dict(facecolor='black', shrink=0.05), ) plt.ylim(-2, 2) plt.show()
In this basic example, both the xy
(arrow tip) and xytext
locations (text location) are in data coordinates. There are a
variety of other coordinate systems one can choose — see
Basic annotation and Advanced Annotations for
details. More examples can be found in
Annotating Plots.
Logarithmic and other nonlinear axes#
matplotlib.pyplot
supports not only linear axis scales, but also
logarithmic and logit scales. This is commonly used if data spans many orders
of magnitude. Changing the scale of an axis is easy:
plt.xscale(‘log’)
An example of four plots with the same data and different scales for the y axis
is shown below.
# Fixing random state for reproducibility np.random.seed(19680801) # make up some data in the open interval (0, 1) y = np.random.normal(loc=0.5, scale=0.4, size=1000) y = y[(y > 0) & (y < 1)] y.sort() x = np.arange(len(y)) # plot with various axes scales plt.figure() # linear plt.subplot(221) plt.plot(x, y) plt.yscale('linear') plt.title('linear') plt.grid(True) # log plt.subplot(222) plt.plot(x, y) plt.yscale('log') plt.title('log') plt.grid(True) # symmetric log plt.subplot(223) plt.plot(x, y - y.mean()) plt.yscale('symlog', linthresh=0.01) plt.title('symlog') plt.grid(True) # logit plt.subplot(224) plt.plot(x, y) plt.yscale('logit') plt.title('logit') plt.grid(True) # Adjust the subplot layout, because the logit one may take more space # than usual, due to y-tick labels like "1 - 10^{-3}" plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25, wspace=0.35) plt.show()
It is also possible to add your own scale, see matplotlib.scale
for
details.
Total running time of the script: ( 0 minutes 4.124 seconds)
Gallery generated by Sphinx-Gallery
Начнем изучение
пакета matplotlib с наиболее
часто используемой функции plot(). На предыдущем занятии мы с ее
помощью построили простой двумерный график:
import matplotlib.pyplot as plt plt.plot([1, 2, -6, 0, 4]) plt.show()
Также обратите
внимание, что мы обращаемся к ветке matplotlib.pyplot для вызова этой
функции. В целом, именно модуль pyplot отвечает за отображение разных
графиков – это «рабочая лошадка» пакета matplotlib.
Давайте первым
делом разберемся, что на вход принимает эта функция и что она, фактически,
делает. В нашей программе мы передаем ей обычный список языка Python. В
действительности же, все входные данные должны соответствовать массивам пакета numpy, то есть, иметь
тип:
numpy.array
Поэтому,
указанный список можно сначала преобразовать в массив numpy:
import numpy as np y = np.array([1, 2, -6, 0, 4])
А, затем, передать его функции plot():
Визуально,
результат будет тем же. Вообще, почти все функции пакета matplotlib работают именно
с массивами numpy: принимают их в
качестве аргументов или возвращают. Поэтому при работе с matplotlib желательно
знать основы numpy. Если у вас
есть пробелы в этих знаниях, то смотрите плейлист по этой теме:
Итак, указывая
всего один аргумент в функции plot() он интерпретируется как множество
точек по ординате (координате Oy). Соответственно, координата x формируется
автоматически как индексы элементов массива y:
Но мы можем
значения по абсциссе указывать и самостоятельно, например, так:
x = np.array([4, 5, 6, 7, 8]) y = np.array([1, 2, -6, 0, 4]) plt.plot(x, y)
Теперь значения
по оси Ox будут лежать в
диапазоне от 4 до 8. Причем, функция plot() при
отображении этих данных делает одну простую вещь – она соединяет прямыми линиями
точки с указанными координатами:
Но это значит,
если указать точки в узлах квадрата, то будет нарисован квадрат на плоскости?
Давайте проверим. Запишем следующие координаты:
x = np.array([1, 1, 5, 5, 1]) y = np.array([1, 5, 5, 1, 1]) plt.plot(x, y)
И действительно,
видим квадрат в координатных осях. Также это означает, что мы можем рисовать
графики с разными шагами по оси абсцисс, например, так:
y = np.arange(0, 5, 1) # [0, 1, 2, 3, 4] x = np.array([a*a for a in y]) # [ 0, 1, 4, 9, 16] plt.plot(x, y)
В результате, мы
увидим не прямую линию, а изогнутую:
Вот так гибко и
интуитивно понятно обрабатывает функция plot() входные
данные.
Давайте сразу на
график наложим сетку, чтобы он выглядел более информативно. Для этого достаточно
прописать строчку:
Далее, если нам
нужно в этих же осях отобразить еще один график, то это можно сделать так:
y = np.arange(0, 5, 1) x = np.array([a*a for a in y]) y2 = [0, 1, 2, 3] x2 = [i+1 for i in y2] plt.plot(x, y, x2, y2)
Причем, оба
графика отображаются совершенно независимо. В частности, они здесь имеют разное
число точек. Тем не менее, никаких проблем не возникает и мы видим следующую
картину:
Это потрясающая
гибкость пакета matplotlib значительно облегчает жизнь
инженерам-программистам. Здесь не надо задумываться о таких мелочах, как
согласованность данных. Все будет показано так, как сформировано.
Соответственно,
указывая следующие пары в функции plot(), будут
отображаться все новые и новые графики в текущих координатах. Но можно сделать
и по-другому. Вызвать функцию plot() несколько раз подряд, например:
plt.plot(x, y) plt.plot(x2, y2)
Получим
аналогичный эффект – два графика в одних координатах. Такая реализация возможна
благодаря объектно-ориентированной архитектуре пакета matplotlib. Здесь
координатные оси – это объект Axes. Соответственно, вызывая функцию plot() снова и
снова, в этот объект помещают новые и новые данные для каждого отдельного
графика:
Но откуда взялся
объект Axes, если мы его
нигде не создавали? Все просто. Он создается автоматически при первом вызове
функции plot(), если ранее,
до этого не было создано ни одного Axes. А раз
создается система координат, то создается и объект Figure, на котором
размещаются оси. Поэтому в нашей программе, при первом вызове функции plot() было создано
два объекта:
- Figure – объект для
отображения всех данных, связанных с графиком; - Axes – двумерная
координатная ось декартовой системы.
Позже мы увидим,
как можно самостоятельно создавать эти объекты и использовать при оформлении графиков.
А пока продолжим рассмотрение базовых возможностей функции plot().
Изменение стилей линий у графиков
Если третьим
параметром в plot() указать
строку с двумя дефисами:
то график будет
изображен не сплошной линией, а штрихами. Какие еще варианты типа линий
возможны? Они приведены в следующей таблице:
Обозначение |
Описание |
‘-‘ |
Непрерывная |
‘—‘ |
Штриховая |
‘-.’ |
Штрихпунктирная |
‘:’ |
Пунктирная |
‘None’ или ‘ ‘ |
Без |
Например, для
второго графика мы можем указать пунктирную линию:
Функция plot возвращает
список на объекты Line2D. Если записать вызов в виде:
lines = plt.plot(x, y, '--') print(lines)
то в консоли
увидим список из одного объекта, так как функция отображает один график. Через
этот объект можно непосредственно управлять графиком, например, поменять тип
линии:
plt.setp(lines, linestyle='-.')
Здесь
используется еще одна функция setp() для настройки свойств объектов, в
данном случае линейного графика.
Если же мы
отобразим два графика одной функцией plot():
lines = plt.plot(x, y, '--', x2, y2, ':')
то коллекция lines будет содержать
два объекта Line2D. Далее,
назначим им стиль:
plt.setp(lines, linestyle='-.')
Теперь они оба
будут отображены штрихпунктирной линией.
Изменение цвета линий графиков
Помимо типа
линий у графиков, конечно же, можно менять и их цвет. В самом простом варианте
достаточно после стиля указать один из символов предопределенных цветов:
<p align=center>{'b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'}
Цвет можно
понять по английскому названию указанной первой буквы. Например,
b = blue, r = red, g = green, c = cyan, w = white, и т.д.
Давайте изменим
цвет у наших графиков, указав символы g и m:
lines = plt.plot(x, y, '--g', x2, y2, ':m')
Как видите, все
предельно просто. Или же можно использовать именованный параметр color (или просто
букву c) для более
точной настройки цвета:
lines = plt.plot(x, y, '--g', x2, y2, ':m', color='r')
В данном случае
оба графика будут отображены красным. Преимущество этого параметра в
возможности указания цвета не только предопределенными символами, но, например,
в шестнадцатиричной записи:
lines = plt.plot(x, y, '--g', x2, y2, ':m', color='#0000CC')
Или в виде
кортежей формата:
RGB и RGBA
lines = plt.plot(x, y, '--g', x2, y2, ':m', color=(0, 0, 0)) lines = plt.plot(x, y, '--g', x2, y2, ':m', c=(0, 0, 0, 0.5))
В последней строчке
использовано второе имя параметра color. Это основные
способы задания цветов. Причем, не только для типов линий графиков, но и при
работе с другими объектами пакета matplotlib. Так что эта
информация в дальнейшем нам еще пригодится.
Изменение маркеров точек у графиков
Наконец, можно
поменять тип маркеров у точек. Для этого в форматную строку достаточно
прописать один из предопределенных символов. Например, вот такая запись:
отображает
график с круглыми точками:
Какие типы
маркеров еще могут быть? Они перечислены в таблице ниже:
Обозначение |
Описание |
‘o’ |
|
‘v’ |
|
‘^’ |
|
‘<‘ |
|
‘>’ |
|
‘2’ |
|
‘3’ |
|
‘4’ |
|
‘s’ |
|
‘p’ |
|
‘*’ |
|
‘h’ |
|
‘H’ |
|
‘+’ |
|
‘x’ |
|
‘D’ |
|
‘d’ |
|
‘|’ |
|
‘_’ |
|
Используются все
эти символы очевидным образом. Причем, записывать их можно в любом порядке с
другими форматными символами:
lines = plt.plot(x, y, '-go', x2, y2, 's:m')
отобразится
следующий график:
Другой способ
определения маркера – использование параметра marker:
lines = plt.plot(x, y, '-go', x2, y2, 's:m', marker='d')
В этом случае
для обоих графиков будет присвоен один и тот же маркер типа ‘d’. Для задания
цвета маркера, отличного от цвета линии, применяется параметр markerfacecolor:
lines = plt.plot(x, y, '-go', x2, y2, 's:m', marker='d', markerfacecolor='w')
Здесь мы выбрали
белый цвет заливки и графики теперь выглядят так:
Именованные параметры функций setp() и plot()
Все эти же
действия по оформлению графика можно выполнять и с помощью функции setp(). Например,
записав следующую строчку:
plt.setp(lines[0], linestyle='-.', marker='s', markerfacecolor='b', linewidth=4)
получим
отображение графика штрихпунктирной линией, квадратным маркером с синей
заливкой и толщиной линии, равной 4 пиксела. Какие еще именованные параметры есть
у функций setp() и plot()? В таблице
ниже я привел основные из них:
Параметр |
Описание |
alpha |
Степень |
color |
Цвет |
dash_capstyle |
Стиль |
dash_joinstyle |
Стиль |
data |
Данные |
linestyle |
Стиль |
linewidth |
Толщина |
marker |
Маркер |
markeredgecolor |
Цвет |
markeredgewidth mew |
Толщина |
markerfacecolor |
Цвет |
markersize |
Размер |
solid_capstyle |
Стиль |
solid_joinstyle |
Стиль |
visible |
Показать/скрыть |
xdata |
Значения |
ydata |
Значения |
Более подробную
информацию о параметрах для оформления графиков смотрите в документации по matplotlib.
Заливка областей графика
Наконец, можно
делать заливку областей графика с помощью функции:
fill_between(x,
y1, y2=0, where=None, interpolate=False, step=None, *, data=None,
**kwargs)
Основные
параметры здесь следующие:
- x, y1 – массивы
значений координат x и функции y1; - y2 – массив (или
число) для второй кривой, до которой производится заливка; - where – массив
булевых элементов, который определяет области для заливки.
В самом простом
случае эту функцию можно использовать так:
x = np.arange(-2*np.pi, 2*np.pi, 0.1) y = np.cos(x) plt.plot(x, y) plt.fill_between(x, y) plt.show()
У нас получилась
косинусоида с заливкой между значениями функции y и осью абсцисс y2 = 0. Если
третьим параметром указать другое число, отличное от нуля, например, 0,5:
plt.fill_between(x, y, 0.5)
то получим
следующий эффект:
А если
дополнительно еще сделать ограничение на выбор заливаемого региона, когда y < 0:
plt.fill_between(x, y, 0.5, where=(y < 0))
то получим такую
картину:
Также можно
вызвать эту функцию два раза подряд:
plt.fill_between(x, y, where=(y < 0), color='r', alpha=0.5) plt.fill_between(x, y, where=(y > 0), color='g', alpha=0.5)
и сформировать
следующее оформление графика косинусоиды:
Вот так можно с
помощью функции plot() отображать графики в координатных осях и делать их
простое оформление.
Видео по теме
I am making a scatter plot in matplotlib and need to change the background of the actual plot to black. I know how to change the face color of the plot using:
fig = plt.figure()
fig.patch.set_facecolor('xkcd:mint green')
My issue is that this changes the color of the space around the plot. How to I change the actual background color of the plot?
Nick T
25.2k11 gold badges79 silver badges120 bronze badges
asked Dec 30, 2012 at 6:02
2
Use the set_facecolor(color)
method of the axes
object, which you’ve created one of the following ways:
-
You created a figure and axis/es together
fig, ax = plt.subplots(nrows=1, ncols=1)
-
You created a figure, then axis/es later
fig = plt.figure() ax = fig.add_subplot(1, 1, 1) # nrows, ncols, index
-
You used the stateful API (if you’re doing anything more than a few lines, and especially if you have multiple plots, the object-oriented methods above make life easier because you can refer to specific figures, plot on certain axes, and customize either)
plt.plot(...) ax = plt.gca()
Then you can use set_facecolor
:
ax.set_facecolor('xkcd:salmon')
ax.set_facecolor((1.0, 0.47, 0.42))
As a refresher for what colors can be:
matplotlib.colors
Matplotlib recognizes the following formats to specify a color:
- an RGB or RGBA tuple of float values in
[0, 1]
(e.g.,(0.1, 0.2, 0.5)
or(0.1, 0.2, 0.5, 0.3)
);- a hex RGB or RGBA string (e.g.,
'#0F0F0F'
or'#0F0F0F0F'
);- a string representation of a float value in
[0, 1]
inclusive for gray level (e.g.,'0.5'
);- one of
{'b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'}
;- a X11/CSS4 color name;
- a name from the xkcd color survey; prefixed with
'xkcd:'
(e.g.,'xkcd:sky blue'
);- one of
{'tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple', 'tab:brown', 'tab:pink', 'tab:gray', 'tab:olive', 'tab:cyan'}
which are the Tableau Colors from the ‘T10’ categorical palette (which is the default color cycle);- a “CN” color spec, i.e. ‘C’ followed by a single digit, which is an index into the default property cycle (
matplotlib.rcParams['axes.prop_cycle']
); the indexing occurs at artist creation time and defaults to black if the cycle does not include color.All string specifications of color, other than “CN”, are case-insensitive.
answered May 14, 2014 at 4:05
Nick TNick T
25.2k11 gold badges79 silver badges120 bronze badges
3
One method is to manually set the default for the axis background color within your script (see Customizing matplotlib):
import matplotlib.pyplot as plt
plt.rcParams['axes.facecolor'] = 'black'
This is in contrast to Nick T’s method which changes the background color for a specific axes
object. Resetting the defaults is useful if you’re making multiple different plots with similar styles and don’t want to keep changing different axes
objects.
Note: The equivalent for
fig = plt.figure()
fig.patch.set_facecolor('black')
from your question is:
plt.rcParams['figure.facecolor'] = 'black'
answered Nov 2, 2016 at 1:13
BurlyPaulsonBurlyPaulson
1,0091 gold badge7 silver badges4 bronze badges
1
Something like this? Use the axisbg
keyword to subplot
:
>>> from matplotlib.figure import Figure
>>> from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
>>> figure = Figure()
>>> canvas = FigureCanvas(figure)
>>> axes = figure.add_subplot(1, 1, 1, axisbg='red')
>>> axes.plot([1,2,3])
[<matplotlib.lines.Line2D object at 0x2827e50>]
>>> canvas.print_figure('red-bg.png')
(Granted, not a scatter plot, and not a black background.)
answered Dec 30, 2012 at 7:26
2
Simpler answer:
ax = plt.axes()
ax.set_facecolor('silver')
petezurich
8,7309 gold badges40 silver badges56 bronze badges
answered May 21, 2020 at 23:07
LeighLeigh
4985 silver badges11 bronze badges
0
If you already have axes
object, just like in Nick T‘s answer, you can also use
ax.patch.set_facecolor('black')
answered May 28, 2014 at 9:33
Mathias711Mathias711
6,5584 gold badges41 silver badges58 bronze badges
0
The easiest thing is probably to provide the color when you create the plot :
fig1 = plt.figure(facecolor=(1, 1, 1))
or
fig1, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, facecolor=(1, 1, 1))
answered May 3, 2019 at 19:03
FlonksFlonks
4153 silver badges8 bronze badges
1
One suggestion in other answers is to use ax.set_axis_bgcolor("red")
. This however is deprecated, and doesn’t work on MatPlotLib >= v2.0.
There is also the suggestion to use ax.patch.set_facecolor("red")
(works on both MatPlotLib v1.5 & v2.2). While this works fine, an even easier solution for v2.0+ is to use
ax.set_facecolor("red")
Demis
4,9954 gold badges22 silver badges33 bronze badges
answered Apr 13, 2017 at 11:30
2
In addition to the answer of NickT, you can also delete the background frame by setting it to «none» as explain here: https://stackoverflow.com/a/67126649/8669161
import matplotlib.pyplot as plt
plt.rcParams['axes.facecolor'] = 'none'
answered Apr 16, 2021 at 14:06
I think this might be useful for some people:
If you want to change the color of the background that surrounds the figure, you can use this:
fig.patch.set_facecolor('white')
So instead of this:
you get this:
Obviously you can set any color you’d want.
P.S. In case you accidentally don’t see any difference between the two plots, try looking at StackOverflow using darkmode.
answered Jul 8, 2022 at 10:58
waykikiwaykiki
8721 gold badge9 silver badges17 bronze badges
2
17 авг. 2022 г.
читать 2 мин
Самый простой способ изменить цвет фона графика в Matplotlib — использовать аргумент set_facecolor() .
Если вы определяете фигуру и ось в Matplotlib, используя следующий синтаксис:
fig, ax = plt.subplots()
Затем вы можете просто использовать следующий синтаксис для определения цвета фона графика:
ax.set_facecolor('pink')
В этом руководстве представлено несколько примеров использования этой функции на практике.
Пример 1. Установка цвета фона с использованием имени цвета
В следующем коде показано, как установить цвет фона графика Matplotlib, используя имя цвета:
import matplotlib.pyplot as plt
#define plot figure and axis
fig, ax = plt.subplots()
#define two arrays for plotting
A = [3, 5, 5, 6, 7, 8]
B = [12, 14, 17, 20, 22, 27]
#create scatterplot and specify background color to be pink
ax.scatter (A, B)
ax.set_facecolor('pink')
#display scatterplot
plt.show()
Пример 2. Установка цвета фона с помощью шестнадцатеричного кода цвета
В следующем коде показано, как установить цвет фона графика Matplotlib с помощью шестнадцатеричного кода цвета:
import matplotlib.pyplot as plt
#define plot figure and axis
fig, ax = plt.subplots()
#define two arrays for plotting
A = [3, 5, 5, 6, 7, 8]
B = [12, 14, 17, 20, 22, 27]
#create scatterplot and specify background color to be pink
ax.scatter (A, B)
ax.set_facecolor('#33FFA2')
#display scatterplot
plt.show()
Пример 3: установка цвета фона для определенного подграфика
Иногда у вас будет более одного графика Matplotlib. В этом случае вы можете использовать следующий код, чтобы указать цвет фона для одного графика:
import matplotlib.pyplot as plt
#define subplots
fig, ax = plt.subplots(2, 2)
fig. tight_layout ()
#define background color to use for each subplot
ax[0,0].set_facecolor('blue')
ax[0,1].set_facecolor('pink')
ax[1,0].set_facecolor('green')
ax[1,1].set_facecolor('red')
#display subplots
plt.show()
Связанный: Как настроить интервал между подграфиками Matplotlib