Столбчатая диаграмма

Столбчатая диаграмма — это визуальное представление с использованием прямоугольных столбцов, где длина каждого столбца соответствует значению. Визуализацию «столбчатая диаграмма» удобно использовать, когда нужно сравнить значения по разным категориям или периодам времени. Столбцы могут отображаться горизонтально или вертикально, а также группироваться или складываться в стек для более сложного анализа данных.

Визуализации «столбчатая диаграмма»

Визуализацию «столбчатая диаграмма» можно использовать, если нужно показать:

  • Распределение населения по возрасту или местоположению
  • Использование CPU по приложениям
  • Продажи по подразделениям
  • Распределение затрат на серверы

Настройка столбчатой диаграммы

Следующее видео показывает, как создать и настроить визуализацию «столбчатая диаграмма»:

Give it a try using Grafana Play
Give it a try using Grafana Play

With Grafana Play, you can explore and see how it works, learning from practical examples to accelerate your development. This feature can be seen on Grafana Bar Charts and Pie Charts.

Поддерживаемые форматы данных

Чтобы создать визуализацию «столбчатая диаграмма», нужен набор данных, содержащий одно строковое поле или поле времени (столбец) и как минимум одно числовое поле, а лучше больше одного, чтобы использовать возможности визуализации в полной мере.

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

Пример 1

Group Value1 Value2 Value3
uno 5 3 2

Пример столбчатой диаграммы с одной строкой

Если текстовых полей или полей времени больше одного, по умолчанию визуализация использует первое из них, но это можно изменить в параметре оси x, как описано в разделе Параметры столбчатой диаграммы.

Пример 2

Если набор данных содержит несколько строк, визуализация отображает несколько групп столбцов, где каждая группа содержит несколько столбцов, представляющих все числовые значения строки.

Group Value1 Value2 Value3
uno 5 3 2
dos 10 6 4
tres 20 8 2

Пример столбчатой диаграммы с несколькими строками

Хотя первое поле может быть основано на времени и с помощью столбчатой диаграммы можно строить временные ряды, для больших объёмов данных временных рядов мы рекомендуем использовать визуализацию «временной ряд» и настроить её отображение в виде столбцов.

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

Применение фильтров из столбчатой диаграммы

В столбчатых диаграммах можно применять фильтры прямо из визуализации. Фильтры доступны, когда поле оси x поддерживает фильтрацию, а источник данных поддерживает фильтры детализации дашборда, например Prometheus или Loki.

Чтобы отобразить кнопку фильтра, наведите курсор на столбец со значением, по которому нужно отфильтровать, и щёлкните по столбцу:

Кнопка фильтра в подсказке столбчатой диаграммы

Подробнее о применении фильтров таким способом см. в разделе Cross-filtering.

Свойство переопределения Transform

Используйте свойство переопределения Graph styles > Transform, чтобы преобразовывать значения рядов, не влияя на значения, отображаемые в подсказке, контекстном меню или легенде. Доступны следующие варианты преобразования:

  • Constant — показывать первое значение как константную линию.
  • Negative Y transform — отражать результаты в отрицательные значения по оси y.

Параметры конфигурации

The following section describes the configuration options available in the panel editor pane for this visualization. These options are, as much as possible, ordered as they appear in Grafana.

Параметры панели

In the Panel options section of the panel editor pane, set basic options like panel title and description, as well as panel links. To learn more, refer to Configure panel options.

Параметры столбчатой диаграммы

Используйте эти параметры, чтобы уточнить визуализацию.

Option Description
X Axis Specify which field is used for the x-axis.
Orientation Choose from:
  • Auto - Grafana decides the bar orientation based on the panel dimensions.
  • Horizontal - Will make the X axis the category axis.
  • Vertical - Will make the Y axis the category axis.
Rotate x-axis tick labels When the graph is vertically oriented, this setting rotates the labels under the bars. This setting is useful when bar chart labels are long and overlap.
X-axis tick label max length Sets the maximum length of bar chart labels. Labels longer than the maximum length are truncated, and appended with .... This option is available when Rotate x-axis tick labels isn’t 0.
X-axis labels minimum spacing Sets the minimum spacing between x-axis labels. Depending on your choice, you can select the RTL checkbox to require space from the right side. Choose from:
  • None - All tick marks are shown.
  • Small - 100 pixels of space is required between labels.
  • Medium - 200 pixels of space is required between labels.
  • Large - 300 pixels of space is required between labels.
Show values This controls whether values are shown. Values are shown on top or to the left of bars. Choose from:
  • Auto Values will be shown if there is space.
  • Always Always show values.
  • Never Never show values.
Stacking Controls bar chart stacking. Choose from:
  • Off: Bars will not be stacked.
  • Normal: Bars will be stacked on each other.
  • 100%: Bars will be stacked on each other, and the height of each bar is the percentage of the total height of the stack.
Group width Controls the width of groups. 1 = Max width, 0 = Min width. This option is hidden when stacking is enabled or when the chart has only one numeric field.
Bar width Controls the width of bars. 1 = Max width, 0 = Min width.
Bar radius Controls the radius of the bars. Choose from:
  • 0 = Minimum radius
  • 0.5 = Maximum radius
Highlight full area on hover Controls if the entire surrounding area of the bar is highlighted when you hover over the bar. This option is available only when Stacking is Off.
Color by field Use the color value for a sibling field to color each bar value.
Line width Controls line width of the bars. This is a field option and can be set in field defaults or overrides.
Fill opacity Controls the fill opacity of bars. This is a field option and can be set in field defaults or overrides.
Gradient mode Set the mode of the gradient fill. Fill gradient is based on the line color. To change the color, use the standard color scheme field option. Gradient appearance is influenced by the Fill opacity setting. This is a field option and can be set in field defaults or overrides.

Режим градиента

Задаёт режим градиентной заливки. Градиент заливки основан на цвете линии. Чтобы изменить цвет, используйте стандартный параметр поля «цветовая схема». На внешний вид градиента влияет параметр Fill opacity. Доступны следующие варианты:

  • None — без градиентной заливки. Это значение по умолчанию.
  • Opacity — прозрачность градиента рассчитывается на основе значений по оси y. Непрозрачность заливки растёт вместе со значениями по оси Y.
  • Hue — цвет градиента формируется на основе оттенка цвета линии.
  • Scheme — столбец получает цвет градиента, заданный выбором Standard options > Color scheme.
    • From thresholds — если в Color scheme выбрано From thresholds (by value), каждый столбец получает цвет заданного порога.

      Цветовая схема From thresholds
      Цветовая схема: From thresholds
    • Gradient color schemes — на следующем изображении показана столбчатая диаграмма с выбранной цветовой схемой Green-Yellow-Red (by value).

      Цветовая схема Green-Yellow-Red
      Цветовая схема: Green-Yellow-Red

Параметры подсказок

Tooltip options control the information overlay that appears when you hover over data points in the visualization.

Option Description
Tooltip mode When you hover your cursor over the visualization, Grafana can display tooltips. Choose how tooltips behave.
Values sort order This option controls the order in which values are listed in a tooltip.
Hide zeros When you set the Tooltip mode to All, the Hide zeros option is displayed. This option controls whether or not series with 0 values are shown in the list in the tooltip.
Max width Set the maximum width of the tooltip box.
Max height Set the maximum height of the tooltip box. The default is 600 pixels.

Tooltip mode

When you hover your cursor over the visualization, Grafana can display tooltips. Choose how tooltips behave.

  • Single - The hover tooltip shows only a single series, the one that you are hovering over on the visualization.
  • All - The hover tooltip shows all series in the visualization. Grafana highlights the series that you are hovering over in bold in the series list in the tooltip.
  • Hidden - Do not display the tooltip when you interact with the visualization.

Use an override to hide individual series from the tooltip.

Values sort order

When you set the Tooltip mode to All, the Values sort order option is displayed. This option controls the order in which values are listed in a tooltip. Choose from the following:

  • None - Grafana automatically sorts the values displayed in a tooltip.
  • Ascending - Values in the tooltip are listed from smallest to largest.
  • Descending - Values in the tooltip are listed from largest to smallest.

Параметры легенды

Legend options control the series names and statistics that appear under or to the right of the graph. For more information about the legend, refer to Configure a legend.

Option Description
Visibility Toggle the switch to turn the legend on or off.
Mode Use these settings to define how the legend appears in your visualization. List displays the legend as a list. This is a default display mode of the legend. Table displays the legend as a table.
Placement Choose where to display the legend. Bottom places the legend below the graph. Right places the legend to the right of the graph.
Width Control how wide the legend is when placed on the right side of the visualization. The value may be a basic pixel width or a more complex CSS width property such as max(200px, 20%). This option is only displayed if you set the legend placement to Right.
Limit Limit how many series items are shown by default. The rest become expandable using a Show all link.
Values Choose which of the standard calculations to show in the legend. You can have more than one.
Overflow Control how overflow for long series names is handled. Ellipsis truncates the series names with “…” at the end. Wrap word-wraps the series names to multiple lines. This option is only displayed if you set the legend placement to Right and mode is Table.

Размер текста

Введите Value, чтобы изменить размер текста на столбчатой диаграмме.

Оси

Используйте следующие параметры полей, чтобы уточнить отображение осей.

О настройке нескольких осей y см. в разделе Несколько осей y.

Некоторые параметры поля не влияют на визуализацию, пока вы не щёлкнете вне редактируемого поля параметра или не нажмёте Enter.

Option Description
Placement Select the placement of the Y-axis. Choose from:
  • Auto - Grafana automatically assigns Y-axis to the series. When there are two or more series with different units, then Grafana assigns the left axis to the first unit and right to the following units.
  • Left - Display all Y-axes on the left side.
  • Right - Display all Y-axes on the right side.
  • Hidden - Hide all axes. To selectively hide axes, add a field override that targets specific fields.
Label Set a Y-axis text label. If you have more than one Y-axis, then you can assign different labels with an override.
Width Set a fixed width of the axis. By default, Grafana dynamically calculates the width of an axis.

By setting the width of the axis, data whose axes types are different can share the same display proportions. This makes it easier to compare more than one graph’s worth of data because the axes are not shifted or stretched within visual proximity of each other.
Show grid lines Set whether grid lines are displayed in the chart. Choose from:
  • Auto - Grafana automatically determines whether grid lines are displayed.
  • On - Grid lines are always displayed.
  • Off - Grid lines are never displayed
Color Choose whether the axis color is the Text or Series color.
Show border Toggle the switch to hide or display the border.
Scale Set how the y-axis is split. Choose from:
  • Linear
  • Logarithmic - Choose between log base 2 or log base 10.
  • Symlog - Uses a symmetrical logarithmic scale. Choose between log base 2 or log base 10, allowing for negative values.
Centered zero Set the y-axis so it’s centered on zero.
Soft min and soft max Set a Soft min or soft max option for better control of Y-axis limits. By default, Grafana sets the range for the Y-axis automatically based on the dataset.

Soft min и soft max

Задайте параметры Soft min или soft max для более точного управления пределами оси Y. По умолчанию Grafana автоматически задаёт диапазон оси Y исходя из набора данных.

Настройки Soft min и soft max помогают не превращать небольшие всплески в горы, когда данные в основном плоские, а жёсткие min или max, заданные стандартными параметрами минимума и максимума, не позволяют кратковременным пикам сгладить полезные детали, обрезая пики после определённой точки.

Можно задать стандартные параметры min/max, чтобы определить жёсткие пределы оси Y. Подробнее см. в разделе Определения стандартных параметров.

Multiple y-axes

In some cases, you might want to display multiple y-axes. For example, if you have a dataset showing both temperature and humidity over time, you might want to show two y-axes with different units for the two series.

You can configure multiple y-axes and control where they’re displayed in the visualization by adding field overrides. This example of a dataset that includes temperature and humidity describes how you can configure that. Repeat the steps for every y-axis you wish to display.

Стандартные параметры

Standard options in the panel editor pane let you change how field data is displayed in your visualizations. When you set a standard option, the change is applied to all fields or series. For more granular control over the display of fields, refer to Configure overrides.

Option Description
Unit Choose which unit a field should use.
Min/Max Set the minimum and maximum values used in percentage threshold calculations or leave these field empty for them to be calculated automatically.
Field min/max Enable Field min/max to have Grafana calculate the min or max of each field individually, based on the minimum or maximum value of the field.
Decimals Specify the number of decimals Grafana includes in the rendered value.
Display name Set the display title of all fields. You can use variables in the field title.
Color scheme Set single or multiple colors for your entire visualization.
No value Enter what Grafana should display if the field value is empty or null. The default value is a hyphen (-).

To learn more, refer to Configure standard options.

Ссылки и действия для данных

Data links allow you to link to other panels, dashboards, and external resources and actions let you trigger basic, unauthenticated, API calls. In both cases, you can carry out these tasks while maintaining the context of the source panel.

For each data link, set the following options:

  • Title
  • URL
  • Open in new tab
  • One click - Opens the data link with a single click. Only one data link can have One click enabled at a time.

For each action, define the following API call settings:

Option Description
Title A human-readable label for the action that’s displayed in the UI.
Confirmation message A descriptive prompt to confirm or cancel the action.
Connection Specify how the action’s HTTP request is sent. Choose from: Direct from browser or routed through a configured data source.
Method Select from POST, PUT, or GET.
URL The request URL.

To add a variable, click in the URL field and enter $ or press Ctrl+Space or Cmd+Space to see a list of available variables.

Variables Key and Name pairs with a type selection. Click the + icon to add as many variables as you need. To add a variable to the request, prefix the key with $. You can set the values for the variables when performing an action.
Query parameters Key and Value pairs. Click the + icon to add as many key/value pairs as you need.
Headers Comprised of Key and Value pairs and a Content-Type.

Click the + icon to add as many key/value pairs as you need.

Content-Type Select from the following: application/json, text/plain, application/XML, and application/x-www-form-urlencoded.
Body The body of the request.

To learn more, refer to Configure data links and actions.

Сопоставления значений

Value mapping is a technique you can use to change how data appears in a visualization.

For each value mapping, set the following options:

  • Condition - Choose what’s mapped to the display text and (optionally) color:
    • Value - Specific values
    • Range - Numerical ranges
    • Regex - Regular expressions
    • Special - Special values like Null, NaN (not a number), or boolean values like true and false
  • Display text
  • Color (Optional)
  • Icon (Canvas only)

To learn more, refer to Configure value mappings.

Пороги

A threshold is a value or limit you set for a metric that’s reflected visually when it’s met or exceeded. Thresholds are one way you can conditionally style and color your visualizations based on query results.

For each threshold, set the following options:

Option Description
Value Set the value for each threshold.
Thresholds mode Choose from Absolute and Percentage.
Show thresholds Choose from a variety of display options including not displaying thresholds at all.

To learn more, refer to Configure thresholds.

Переопределения полей

Overrides allow you to customize visualization settings for specific fields or series. When you add an override rule, it targets a particular set of fields and lets you define multiple options for how that field is displayed.

Choose from the following override options:

Option Description
Fields with name Select a field from the list of all available fields.
Field with name matching regex Specify fields to override with a regular expression.
Fields with type Select fields by type, such as string, numeric, or time.
Fields returned by query Select all fields returned by a specific query, such as A, B, or C.
Fields with values Select all fields returned by your defined reducer condition, such as Min, Max, Count, Total.

To learn more, refer to Configure field overrides.