- Matplotlib. Урок 4.3. Визуализация данных. Столбчатые и круговые диаграммы
- Столбчатые диаграммы
- Групповые столбчатые диаграммы
- Диаграмма с errorbar элементом
- Круговые диаграммы
- Классическая круговая диаграмма
- Вложенные круговые диаграммы
- Круговая диаграмма в виде бублика
- P.S.
- matplotlib.pyplot.bar#
- Matplotlib Bar chart
- Bar chart code
- Bar chart comparison
- Stacked bar chart
Matplotlib. Урок 4.3. Визуализация данных. Столбчатые и круговые диаграммы
В этому уроке изучим особенности работы со столбчатой и круговой диаграммами.
Столбчатые диаграммы
Для визуализации категориальных данных хорошо подходят столбчатые диаграммы. Для их построения используются функции:
bar() – для построения вертикальной диаграммы
barh() – для построения горизонтальной диаграммы.
Построим простую диаграмму:
np.random.seed(123) groups = [f"P" for i in range(7)] counts = np.random.randint(3, 10, len(groups)) plt.bar(groups, counts)
Если заменим bar() на barh() получим горизонтальную диаграмму:
Рассмотрим более подробно параметры функции bar() :
- x : набор величин
- x координаты столбцов
- Высоты столбцов
- Ширина столбцов
- y координата базы
- Выравнивание по координате x .
- color : скалярная величина, массив или optional
- Цвет столбцов диаграммы
- Цвет границы столбцов
- Ширина границы
- Метки для столбца
- Величина ошибки для графика. Выставленное значение удаляется/прибавляется к верхней (правой – для горизонтального графика) границе. Может принимать следующие значения:
- скаляр: симметрично +/- для всех баров
- shape(N,) : симметрично +/- для каждого бара
- shape(2,N) : выборочного – и + для каждого бара. Первая строка содержит нижние значения ошибок, вторая строка – верхние.
- None : не отображать значения ошибок. Это значение используется по умолчанию.
- Цвет линии ошибки.
- Включение логарифмического масштаба для оси y
- Ориентация: вертикальная или горизонтальная.
Построим более сложный пример, демонстрирующий работу с параметрами:
import matplotlib.colors as mcolors bc = mcolors.BASE_COLORS np.random.seed(123) groups = [f"P" for i in range(7)] counts = np.random.randint(0, len(bc), len(groups)) width = counts*0.1 colors = [["r", "b", "g"][int(np.random.randint(0, 3, 1))] for _ in counts] plt.bar(groups, counts, width=width, alpha=0.6, bottom=2, color=colors, edgecolor="k", linewidth=2)
Групповые столбчатые диаграммы
Используя определенным образом подготовленные данные можно строить групповые диаграммы:
cat_par = [f"P" for i in range(5)] g1 = [10, 21, 34, 12, 27] g2 = [17, 15, 25, 21, 26] width = 0.3 x = np.arange(len(cat_par)) fig, ax = plt.subplots() rects1 = ax.bar(x - width/2, g1, width, label='g1') rects2 = ax.bar(x + width/2, g2, width, label='g2') ax.set_title('Пример групповой диаграммы') ax.set_xticks(x) ax.set_xticklabels(cat_par) ax.legend()
Диаграмма с errorbar элементом
Errorbar элемент позволяет задать величину ошибки для каждого элемента графика. Для этого используются параметры xerr , yerr и ecolor (для задания цвета):
np.random.seed(123) rnd = np.random.randint cat_par = [f"P" for i in range(5)] g1 = [10, 21, 34, 12, 27] error = np.array([[rnd(2,7),rnd(2,7)] for _ in range(len(cat_par))]).T fig, axs = plt.subplots(1, 2, figsize=(10, 5)) axs[0].bar(cat_par, g1, yerr=5, ecolor="r", alpha=0.5, edgecolor="b", linewidth=2) axs[1].bar(cat_par, g1, yerr=error, ecolor="r", alpha=0.5, edgecolor="b", linewidth=2)
Круговые диаграммы
Классическая круговая диаграмма
Круговые диаграммы – это наглядный способ показать доли компонент в наборе. Они идеально подходят для отчетов, презентаций и т.п. Для построения круговых диаграмм в Matplotlib используется функция pie() .
Пример построения диаграммы:
vals = [24, 17, 53, 21, 35] labels = ["Ford", "Toyota", "BMV", "AUDI", "Jaguar"] fig, ax = plt.subplots() ax.pie(vals, labels=labels) ax.axis("equal")
Рассмотрим параметры функции pie() :
- x: массив
- Массив с размерами долей.
- Если параметр не равен None , то часть долей, который перечислены в передаваемом значении будут вынесены из диаграммы на заданное расстояние, пример диаграммы:
- labels: list, optional , значение по умолчанию: None
- Текстовые метки долей.
- Цвета долей.
- Формат текстовой метки внутри доли, текст – это численное значение показателя, связанного с конкретной долей.
- Расстояние между центром каждой доли и началом текстовой метки, которая определяется параметром autopct .
- Отображение тени для диаграммы.
- Расстояние, на котором будут отображены текстовые метки долей. Если параметр равен None , то метки не будет отображены.
- Задает угол, на который нужно повернуть диаграмму против часовой стрелке относительно оси x .
- Величина радиуса диаграммы.
- Определяет направление вращения – по часовой или против часовой стрелки.
- Словарь параметров, определяющих внешний вид долей.
- Словарь параметров определяющих внешний вид текстовых меток.
- Центр диаграммы.
- Если параметр равен True , то вокруг диаграммы будет отображена рамка.
- Если параметр равен True , то текстовые метки будут повернуты на угол.
Создадим пример, в котором продемонстрируем работу с параметрами функции pie() :
vals = [24, 17, 53, 21, 35] labels = ["Ford", "Toyota", "BMV", "AUDI", "Jaguar"] explode = (0.1, 0, 0.15, 0, 0) fig, ax = plt.subplots() ax.pie(vals, labels=labels, autopct='%1.1f%%', shadow=True, explode=explode, wedgeprops=, rotatelabels=True) ax.axis("equal")
Вложенные круговые диаграммы
Рассмотрим пример построения вложенной круговой диаграммы. Такая диаграмма состоит из двух компонент: внутренняя ее часть является детальным представлением информации, а внешняя – суммарную по заданным областям. Каждая область представляет собой список численных значений, вместе они образуют общий набор данных. Рассмотрим на примере:
fig, ax = plt.subplots() offset=0.4 data = np.array([[5, 10, 7], [8, 15, 5], [11, 9, 7]]) cmap = plt.get_cmap("tab20b") b_colors = cmap(np.array([0, 8, 12])) sm_colors = cmap(np.array([1, 2, 3, 9, 10, 11, 13, 14, 15])) ax.pie(data.sum(axis=1), radius=1, colors=b_colors, wedgeprops=dict(width=offset, edgecolor='w')) ax.pie(data.flatten(), radius=1-offset, colors=sm_colors, wedgeprops=dict(width=offset, edgecolor='w'))
Круговая диаграмма в виде бублика
Построим круговую диаграмму в виде бублика (с отверстием посередине). Это можно сделать через параметр wedgeprops , который отвечает за внешний вид долей:
vals = [24, 17, 53, 21, 35] labels = ["Ford", "Toyota", "BMV", "AUDI", "Jaguar"] fig, ax = plt.subplots() ax.pie(vals, labels=labels, wedgeprops=dict(width=0.5))
P.S.
Вводные уроки по “Линейной алгебре на Python” вы можете найти соответствующей странице нашего сайта . Все уроки по этой теме собраны в книге “Линейная алгебра на Python”.
Если вам интересна тема анализа данных, то мы рекомендуем ознакомиться с библиотекой Pandas. Для начала вы можете познакомиться с вводными уроками. Все уроки по библиотеке Pandas собраны в книге “Pandas. Работа с данными”.
matplotlib.pyplot.bar#
The bars are positioned at x with the given alignment. Their dimensions are given by height and width. The vertical baseline is bottom (default 0).
Many parameters can take either a single value applying to all bars or a sequence of values, one for each bar.
Parameters : x float or array-like
The x coordinates of the bars. See also align for the alignment of the bars to the coordinates.
height float or array-like
width float or array-like, default: 0.8
bottom float or array-like, default: 0
The y coordinate(s) of the bottom side(s) of the bars.
align , default: ‘center’
Alignment of the bars to the x coordinates:
- ‘center’: Center the base on the x positions.
- ‘edge’: Align the left edges of the bars with the x positions.
To align the bars on the right edge pass a negative width and align=’edge’ .
Container with all the bars and optionally errorbars.
Other Parameters : color color or list of color, optional
The colors of the bar faces.
edgecolor color or list of color, optional
The colors of the bar edges.
linewidth float or array-like, optional
Width of the bar edge(s). If 0, don’t draw edges.
tick_label str or list of str, optional
The tick labels of the bars. Default: None (Use default numeric labels.)
label str or list of str, optional
A single label is attached to the resulting BarContainer as a label for the whole dataset. If a list is provided, it must be the same length as x and labels the individual bars. Repeated labels are not de-duplicated and will cause repeated label entries, so this is best used when bars also differ in style (e.g., by passing a list to color.)
xerr, yerr float or array-like of shape(N,) or shape(2, N), optional
If not None, add horizontal / vertical errorbars to the bar tips. The values are +/- sizes relative to the data:
- scalar: symmetric +/- values for all bars
- shape(N,): symmetric +/- values for each bar
- shape(2, N): Separate — and + values for each bar. First row contains the lower errors, the second row contains the upper errors.
- None: No errorbar. (Default)
See Different ways of specifying error bars for an example on the usage of xerr and yerr.
ecolor color or list of color, default: ‘black’
The line color of the errorbars.
capsize float, default: rcParams[«errorbar.capsize»] (default: 0.0 )
The length of the error bar caps in points.
error_kw dict, optional
Dictionary of keyword arguments to be passed to the errorbar method. Values of ecolor or capsize defined here take precedence over the independent keyword arguments.
log bool, default: False
If True, set the y-axis to be log scale.
data indexable object, optional
If given, all parameters also accept a string s , which is interpreted as data[s] (unless this raises an exception).
a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image
Matplotlib Bar chart
Matplotlib may be used to create bar charts. You might like the Matplotlib gallery.
Matplotlib is a python library for visualizing data. You can use it to create bar charts in python. Installation of matplot is on pypi, so just use pip: pip install matplotlib
The course below is all about data visualization:
Bar chart code
A bar chart shows values as vertical bars, where the position of each bar indicates the value it represents. matplot aims to make it as easy as possible to turn data into Bar Charts.
A bar chart in matplotlib made from python code. The code below creates a bar chart:
import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as pltobjects = (‘Python’, ‘C++’, ‘Java’, ‘Perl’, ‘Scala’, ‘Lisp’)
y_pos = np.arange(len(objects))
performance = [10,8,6,4,2,1]plt.bar(y_pos, performance, align=‘center’, alpha=0.5)
plt.xticks(y_pos, objects)
plt.ylabel(‘Usage’)
plt.title(‘Programming language usage’)plt.show()
Matplotlib charts can be horizontal, to create a horizontal bar chart:
import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as pltobjects = (‘Python’, ‘C++’, ‘Java’, ‘Perl’, ‘Scala’, ‘Lisp’)
y_pos = np.arange(len(objects))
performance = [10,8,6,4,2,1]plt.barh(y_pos, performance, align=‘center’, alpha=0.5)
plt.yticks(y_pos, objects)
plt.xlabel(‘Usage’)
plt.title(‘Programming language usage’)plt.show()
Bar chart comparison
You can compare two data series using this Matplotlib code:
import numpy as np
import matplotlib.pyplot as plt# data to plot
n_groups = 4
means_frank = (90, 55, 40, 65)
means_guido = (85, 62, 54, 20)# create plot
fig, ax = plt.subplots()
index = np.arange(n_groups)
bar_width = 0.35
opacity = 0.8rects1 = plt.bar(index, means_frank, bar_width,
alpha=opacity,
color=‘b’,
label=‘Frank’)rects2 = plt.bar(index + bar_width, means_guido, bar_width,
alpha=opacity,
color=‘g’,
label=‘Guido’)plt.xlabel(‘Person’)
plt.ylabel(‘Scores’)
plt.title(‘Scores by person’)
plt.xticks(index + bar_width, (‘A’, ‘B’, ‘C’, ‘D’))
plt.legend()plt.tight_layout()
plt.show()Python Bar Chart comparison
Stacked bar chart
The example below creates a stacked bar chart with Matplotlib. Stacked bar plots show diffrent groups together.
# load matplotlib
import matplotlib.pyplot as plt# data set
x = [‘A’, ‘B’, ‘C’, ‘D’]
y1 = [100, 120, 110, 130]
y2 = [120, 125, 115, 125]# plot stacked bar chart
plt.bar(x, y1, color=‘g’)
plt.bar(x, y2, bottom=y1, color=‘y’)
plt.show()