Lens Visualization Editor

Lens is Kibana's recommended visualization editor. It provides a drag-and-drop interface that intelligently suggests chart types based on the fields you select, making it fast to build effective visualizations without deep aggregation knowledge.

Why Lens?

FeatureLensAggregation-BasedTSVB
Drag and dropYesNoNo
Smart suggestionsYesNoNo
Formula supportYesNoLimited
Multi-layer chartsYesNoYes
Learning curveLowMediumHigh
FlexibilityHighVery HighHigh
Recommended forMost use casesComplex aggsAdvanced time series

Use Lens unless you need a specific feature only available in aggregation-based or TSVB editors.

Opening Lens

From Dashboard

  1. Open or create a dashboard
  2. Click "Create visualization"
  3. Lens opens by default

From Visualize Library

  1. Go to Visualize Library
  2. Click "Create visualization"
  3. Select "Lens"

From Discover

  1. Run a search in Discover
  2. Click "Visualize" in the toolbar
  3. Opens Lens with your current search context

The Lens Interface

┌─────────────────────────────────────────────────────────────┐
│  Data view: [logs-* ▼]           [Save] [Suggestions ▼]     │
├──────────┬──────────────────────────────────────────────────┤
│          │  Chart Type:  [Bar ▼] [Line] [Area] [Pie] [...]  │
│  Field   │ ┌──────────────────────────────────────────────┐ │
│  List    │ │                                              │ │
│          │ │              Visualization                    │ │
│ # bytes  │ │              Preview                         │ │
│ t host   │ │                                              │ │
│ 📅 @time │ │     ████                                     │ │
│ 🔤 status│ │     ████  ███                                │ │
│ ...      │ │     ████  ███  ██                            │ │
│          │ └──────────────────────────────────────────────┘ │
│          │  ┌─────────────────┐  ┌──────────────────────┐  │
│          │  │ Horizontal axis │  │ Vertical axis        │  │
│          │  │ [Drop field]    │  │ [Drop field]         │  │
│          │  └─────────────────┘  └──────────────────────┘  │
│          │  ┌─────────────────┐                             │
│          │  │ Break down by   │                             │
│          │  │ [Drop field]    │                             │
│          │  └─────────────────┘                             │
└──────────┴──────────────────────────────────────────────────┘

Key Areas

  1. Field list (left): All fields from the selected data view
  2. Chart type selector (top): Switch between visualization types
  3. Preview area (center): Live preview of your visualization
  4. Configuration zones (bottom): Drop zones for fields
  5. Suggestions (top-right): Lens recommends alternative chart types

Building Your First Lens Visualization

Step 1: Select Data View

Choose the data view containing your data from the dropdown at the top-left.

Step 2: Drag Fields

Drag fields from the left panel into the configuration zones:

Example: Revenue over time

1. Drag "order_date" to Horizontal axis
   → Lens creates a date histogram automatically

2. Drag "taxful_total_price" to Vertical axis
   → Lens uses "Sum" aggregation by default
   → Preview shows a bar chart

Step 3: Adjust Chart Type

Click the chart type icons to switch:

Lens chose: Bar chart
But you want: Line chart

Click the line chart icon → Visualization updates instantly

Step 4: Refine Configuration

Click on any axis configuration to modify:

Click on "Sum of taxful_total_price":
  - Change function: Sum → Average → Median → Count
  - Change label: "Total Revenue"
  - Change format: Number → Currency

Step 5: Save

Click "Save and return" (to dashboard) or "Save to library" (standalone).

Chart Types in Lens

Bar and Column Charts

Vertical bar: Categories on X-axis, values on Y-axis. Horizontal bar: Categories on Y-axis, values on X-axis.

Configuration:
  Horizontal axis: category.keyword (Top values, 10)
  Vertical axis: Count
  Break down by: (optional) manufacturer.keyword

Options:
  - Stacked / Grouped / Percentage
  - Show value labels
  - Fit to axis bounds

Line Charts

Best for time series and trends.

Configuration:
  Horizontal axis: @timestamp (Date histogram)
  Vertical axis: Average of response_time

Options:
  - Curved / Straight lines
  - Show points
  - Missing values: Skip / Connect / Zero
  - Line thickness

Area Charts

Like line charts but with filled area beneath.

Configuration:
  Horizontal axis: @timestamp
  Vertical axis: Count
  Break down by: response (Top 3 values)

Options:
  - Stacked / Percentage / Overlapping
  - Opacity (fill level)

Pie and Donut Charts

Part-to-whole relationships.

Configuration:
  Slice by: category.keyword (Top values, 5)
  Size by: Sum of taxful_total_price

Options:
  - Pie / Donut / Treemap / Mosaic / Waffle
  - Show labels / percentages
  - Empty size ratio (donut hole size)

Metric

Single large number display.

Configuration:
  Primary metric: Sum of taxful_total_price
  Maximum: 100000 (for progress bar)

Options:
  - Trend line (show sparkline)
  - Color by value (thresholds)
  - Subtitle text
  - Prefix / Suffix ($, %, etc.)

Data Table

Tabular aggregation results.

Configuration:
  Rows: category.keyword (Top 10)
  Metrics:
    - Count
    - Sum of taxful_total_price
    - Average of taxful_total_price

Options:
  - Row totals
  - Column totals
  - Pagination
  - Alignment
  - Dynamic coloring

Gauge

Progress toward a goal.

Configuration:
  Metric: Count
  Goal: 1000
  Band colors:
    - 0-400: Red
    - 400-700: Yellow
    - 700-1000: Green

Types: Arc / Circle / Semi-circle

Heatmap

Two-dimensional density visualization.

Configuration:
  Horizontal axis: day_of_week (Top values, 7)
  Vertical axis: hour_of_day (Intervals, step 1)
  Cell value: Count

Options:
  - Color palette (green-red, blue-red, custom)
  - Show labels in cells
  - Custom value range

Tag Cloud

Word frequency visualization.

Configuration:
  Tags: products.product_name.keyword (Top 50)
  Size by: Count

Options:
  - Orientation (horizontal, vertical, mixed)
  - Min/Max font size

Functions and Formulas

Built-in Functions

Lens provides these aggregation functions:

Metric Functions:

FunctionDescriptionExample
CountNumber of documentsTotal orders
SumTotal of valuesTotal revenue
AverageMean valueAverage order value
Median50th percentileTypical response time
MinLowest valueMinimum price
MaxHighest valueMaximum price
Unique countDistinct valuesUnique visitors
PercentileSpecific percentilep95 response time
Standard deviationValue spreadPrice variability
Last valueMost recent valueCurrent CPU usage
Counter rateRate of a monotonic counterRequests per second

Bucket Functions:

FunctionDescriptionUse
Date histogramTime bucketsTime series
Top valuesMost common valuesTop categories
IntervalsFixed numeric rangesAge groups, price ranges
FiltersCustom query bucketsSpecific segments
Significant termsUnusual termsAnomaly detection

Formula Mode

Lens supports formulas for complex calculations. Click on a metric and select "Formula":

# Basic math
sum(taxful_total_price) / count()

# Percentage
count(kql='response: 200') / count() * 100

# Difference from average
average(response_time) - overall_average(response_time)

# Conditional counting
count(kql='level: "error"') / count() * 100

Formula Syntax

FUNCTIONS
  count()                           Document count
  count(kql='field: value')         Filtered count
  sum(field_name)                   Sum of field
  average(field_name)               Average of field
  min(field_name)                   Minimum
  max(field_name)                   Maximum
  percentile(field_name, 95)        95th percentile
  unique_count(field_name)          Cardinality
  last_value(field_name)            Most recent value
  counter_rate(field_name)          Rate of counter

MATH
  + - * /                           Basic arithmetic
  ()                                Grouping

COMPARISON (for color rules)
  Formulas return numbers - use color rules for thresholds

SPECIAL
  overall_sum(metric)               Total across all buckets
  overall_average(metric)           Average across all buckets
  overall_min(metric)               Min across all buckets
  overall_max(metric)               Max across all buckets
  cumulative_sum(metric)            Running total
  differences(metric)               Change from previous bucket
  moving_average(metric, window=7)  Smoothed trend
  time_scale(metric, unit='1h')     Normalize to time unit

Formula Examples

Error rate percentage:

count(kql='response >= 400') / count() * 100

Revenue per customer:

sum(taxful_total_price) / unique_count(customer_id)

Week-over-week growth:

differences(sum(taxful_total_price))

Moving average (7-day):

moving_average(sum(taxful_total_price), window=7)

Percentage of total:

sum(taxful_total_price) / overall_sum(sum(taxful_total_price)) * 100

Normalized rate (per hour):

time_scale(count(), unit='1h')

Multi-Layer Visualizations

Lens supports multiple layers on a single chart, useful for overlaying different metrics or reference lines.

Adding a Layer

  1. Click "Add layer" at the bottom of the configuration panel
  2. Choose layer type:
Layer TypePurpose
VisualizationAnother data series
Reference lineStatic or dynamic threshold
AnnotationsMark events on the timeline

Example: Response Time with SLA Line

Layer 1 (Visualization):
  Type: Line
  X-axis: @timestamp
  Y-axis: percentile(response_time, 95)
  Label: "p95 Response Time"

Layer 2 (Reference line):
  Value: 500
  Label: "SLA Threshold"
  Color: Red
  Style: Dashed

Example: Error Rate with Deployment Annotations

Layer 1 (Visualization):
  Type: Area
  X-axis: @timestamp
  Y-axis: count(kql='response >= 500')

Layer 2 (Annotations):
  Data view: deployments-*
  Field: deploy_time
  Label: version
  Icon: Flag

Dual Axis

Show two metrics with different scales:

Layer 1 (Left Y-axis):
  Y-axis: Count of requests
  Axis title: "Request Count"
  Position: Left

Layer 2 (Right Y-axis):
  Y-axis: Average response_time
  Axis title: "Avg Response (ms)"
  Position: Right

Customization Options

Legend

Position: Right / Bottom / Top / Left / Hidden
- Show values in legend
- Truncate labels at N characters
- Number of lines per label

Colors

- Custom palette: Choose specific colors per series
- Gradient palettes: For continuous data (heatmaps)
- By value coloring: Threshold-based colors
  - < 100: Green
  - 100-500: Yellow
  - > 500: Red

Axis Settings

Left axis:
  - Title: "Total Revenue ($)"
  - Bounds: Auto / Custom (0 to 10000)
  - Orientation: Horizontal / Vertical

Bottom axis:
  - Title: "Date"
  - Extent: Data bounds / Custom
  - Label rotation: 0° / 45° / 90°

Value Format

Click on a metric to change its display format:

Format options:
  - Number (1,234.56)
  - Percent (0.85 → 85%)
  - Bytes (1536000 → 1.5 MB)
  - Bits (8192 → 8 Kbit)
  - Currency ($1,234.56)
  - Custom (suffix, prefix, decimals)

Suggestions Panel

Lens analyzes your current field selection and suggests alternative visualizations:

  1. Click "Suggestions" in the top-right
  2. Browse recommended chart types
  3. Click one to instantly switch
  4. Undo with Ctrl/Cmd + Z if you don't like it
Example flow:
  You build: Bar chart of top categories by count
  Lens suggests:
    - Pie chart (same data, different view)
    - Treemap (hierarchical view)
    - Table (detailed numbers)
    - Metric (if single category selected)

Practical Examples

Example 1: Operations Dashboard Panels

Request Rate (Line Chart):

Data view: webserver-logs-*
Horizontal axis: @timestamp (auto interval)
Vertical axis: count() with time_scale(count(), unit='1s')
Label: "Requests per Second"

Error Rate (Metric with Trend):

Data view: webserver-logs-*
Primary metric: Formula
  count(kql='response >= 500') / count() * 100
Subtitle: "Server Error Rate"
Format: Percent (1 decimal)
Color rules:
  - < 1%: Green
  - 1-5%: Yellow
  - > 5%: Red
Secondary metric: Trend line (show direction)

Response Time Percentiles (Line Chart, Multi-Layer):

Layer 1:
  X: @timestamp
  Y: percentile(response_time, 50)  → "p50 (Median)"
  Color: Blue

Layer 2 (add layer):
  X: @timestamp
  Y: percentile(response_time, 95)  → "p95"
  Color: Orange

Layer 3 (add layer):
  X: @timestamp
  Y: percentile(response_time, 99)  → "p99"
  Color: Red

Reference line: 500ms SLA threshold (dashed red)

Example 2: E-Commerce Analysis

Revenue vs Orders (Dual Axis):

Layer 1 (left axis):
  X: order_date (weekly)
  Y: sum(taxful_total_price)
  Type: Bar
  Label: "Weekly Revenue"

Layer 2 (right axis):
  X: order_date (weekly)
  Y: count()
  Type: Line
  Label: "Order Count"

Customer Cohort Table:

Type: Data Table
Rows: Split by geoip.country_iso_code (Top 10)
Metrics:
  - unique_count(customer_id) → "Customers"
  - count() → "Orders"
  - sum(taxful_total_price) → "Revenue"
  - Formula: sum(taxful_total_price) / unique_count(customer_id) → "Rev/Customer"

Sort: Revenue descending
Color: Revenue column with gradient

Example 3: Infrastructure Heatmap

Type: Heatmap
Data view: metricbeat-*
X-axis: host.name (Top 20)
Y-axis: Filters:
  - system.cpu.total.pct > 0  → "CPU"
  - system.memory.used.pct > 0 → "Memory"
  - system.filesystem.used.pct > 0 → "Disk"
Cell value: Average of each metric
Palette: Green (0%) to Red (100%)

Tips and Best Practices

Workflow Tips

✅ Start with drag-and-drop, refine with configuration
✅ Use suggestions to explore alternative chart types
✅ Switch to formula mode for complex calculations
✅ Use Ctrl/Cmd+Z to undo changes
✅ Save frequently while building complex visualizations

❌ Don't start with formulas (drag fields first)
❌ Don't ignore suggestions (they often reveal better options)
❌ Don't put too many series on one chart (max 5-7)

Performance Tips

✅ Use Top 5-10 instead of Top 100 for terms
✅ Narrow time range before building visualizations
✅ Use date histogram with reasonable intervals
✅ Prefer count() and sum() over expensive calculations

❌ Avoid percentile() on high-cardinality fields
❌ Avoid unique_count() on text fields (use keyword)
❌ Avoid wide time ranges with small intervals

Design Tips

✅ Choose the right chart type for the data
✅ Label axes clearly with units
✅ Use consistent colors across related panels
✅ Add reference lines for context (SLAs, targets)
✅ Show data labels on metrics and bar charts

❌ Don't use pie charts for more than 7 categories
❌ Don't use 3D effects
❌ Don't rely on color alone (add labels)
❌ Don't truncate axis to exaggerate differences

Summary

In this chapter, you learned:

  • ✅ Why Lens is the recommended visualization editor
  • ✅ The drag-and-drop interface and configuration zones
  • ✅ All chart types available in Lens
  • ✅ Using functions, formulas, and calculations
  • ✅ Building multi-layer charts with reference lines and annotations
  • ✅ Customizing legends, colors, axes, and formats
  • ✅ Practical examples for operations, e-commerce, and infrastructure
  • ✅ Performance and design best practices

Next: Creating pixel-perfect presentations with Canvas!