- Inicio
- Recursos
- Galería Deneb
- Treemap de ventas y margen por subcategoría
Treemap de ventas y margen por subcategoría
¿Qué subcategorías mueven la venta y cuáles la mueven sin ganar dinero? El área de cada rectángulo es su venta y el color, su margen: verde cuando deja margen, rojo cuando pierde. En Contoso salta a la vista Video Game Consoles: el 10 % de la venta con margen negativo.
💡 Cuándo usarlo
Cuando tienes una jerarquía de dos niveles (categoría → subcategoría, región → tienda) y quieres ver a la vez el peso de cada pieza y su rentabilidad. Funciona bien hasta unos 40 rectángulos; con más, los pequeños pierden la etiqueta y solo se leen con el tooltip. Si lo que importa es el orden exacto, usa un gráfico de barras.
Vista previa en vivo
Render con datos de muestra · Vega/Vega-LiteEl resaltado de la categoría al pasar el cursor y el tooltip corren en vivo aquí. El clic en un rectángulo filtra los demás visuales solo dentro de Power BI, porque aquí no hay informe alrededor.
Cargando vista previa… Vista previa renderizada con el runtime de Deneb · MIT © Daniel Marsh-Patrick
¿Te aviso cuando salga un visual nuevo?
Opcional: la descarga no lo necesita. Un correo cada dos semanas como mucho. Y si quieres todos los visuales de pago, está el Pase Deneb.
🧩 Campos que espera
-
__0__CategoryName texto -
__1__SubCategoryName texto -
__2__Total Sales número medida -
__3__Margin % número medida
Arrastra tus campos a Values en este orden.
🎯 Técnica
- Motor
- Vega 5.30.0
- Transforms
- aggregate agregación, filter filtro, formula fórmula calculada, lookup, window ventana (acumulados/ranking)
- Parámetros
-
-
UI_MarginMidpoint: margen que marca el tono medio de la escala de color; por encima, verde más oscuro se cambia en el spec · por defecto 0.15
Y 5 señales internas de cálculo y diseño.
-
- Power BI
-
-
pbiContainerHeight: alto del recuadro del visual, para que el gráfico se ajuste -
pbiContainerWidth: ancho del recuadro del visual, para que el gráfico se ajuste -
pbiCrossFilterApply: filtra el resto del informe con lo que se pulsa -
pbiCrossFilterClear: quita el filtro cruzado del resto del informe -
pbiFormatAutoUnit: abrevia un número grande con su unidad (K, M…), como hace Power BI
-
🛠️ Cómo está hecho
Vega puro: nest arma el árbol con la primera columna y treemap (squarify) reparte el área por la medida. El color es una escala lineal de cuatro tramos (−10 %, 0 %, 15 %, 40 %) y el texto pasa a blanco sobre los tonos oscuros. Cada etiqueta se oculta cuando no cabe. Al pasar el cursor se resalta la categoría; el clic en un bloque filtra el resto del informe por esa subcategoría y el clic en la cabecera, por la categoría entera. Una línea al pie nombra la subcategoría con peor margen. La vista previa usa las 14 subcategorías de Contoso Retail 2023–2024.
Cómo usarlo en Power BI
- Agrega el visual Deneb a tu reporte e ingresa a su editor.
- Arrastra tus campos a Values en este orden: CategoryName , SubCategoryName , Total Sales , Margin % .
- Pega el spec (botón «Copiar spec» arriba) en el editor JSON de Deneb.
- Mapea tus columnas y ajusta a tu gusto. La interactividad nativa ya viene configurada.
Ver el spec Vega completo
{
"$schema": "https://vega.github.io/schema/vega/v5.json",
"description": "Treemap de dos niveles: el área de cada rectángulo es la venta de la subcategoría y su color, el margen. Responde qué subcategorías mueven la venta y cuáles la mueven sin ganar dinero. Por CSalcedoDataBI · https://csalcedodatabi.com/deneb/treemap-ventas-subcategoria",
"usermeta": {
"deneb": {
"build": "1.9.0",
"metaVersion": 1,
"provider": "vega",
"providerVersion": "5.30.0"
},
"interactivity": {
"tooltip": true,
"contextMenu": true,
"selection": true,
"highlight": false,
"dataPointLimit": 100,
"selectionMode": "advanced"
},
"information": {
"uuid": "495859a3-d329-4d5d-b0c8-f8e6a9bd6dff",
"generated": "2026-12-01T05:33:52.812Z",
"name": "Treemap de ventas y margen",
"description": "Sales and Margin Treemap by Subcategory. Pure Vega, no custom DAX. Ficha y vista previa en vivo: https://csalcedodatabi.com/deneb/treemap-ventas-subcategoria. Autor: Cristobal Salcedo Beltrán.",
"author": "Cristobal Salcedo Beltrán"
},
"dataset": [
{
"key": "__0__",
"name": "CategoryName",
"description": "Primer nivel: agrupa los rectángulos (categoría, región, familia…).",
"type": "text",
"kind": "column"
},
{
"key": "__1__",
"name": "SubCategoryName",
"description": "Segundo nivel: un rectángulo por valor (subcategoría, producto, tienda…).",
"type": "text",
"kind": "column"
},
{
"key": "__2__",
"name": "Total Sales",
"description": "Medida que da el área de cada rectángulo. Debe ser positiva.",
"type": "numeric",
"kind": "measure"
},
{
"key": "__3__",
"name": "Margin %",
"description": "Ratio que da el color: rojo por debajo de 0 %, verde hacia el 40 %. Si usas otro ratio, ajusta el dominio de la escala `color`.",
"type": "numeric",
"kind": "measure"
}
]
},
"width": {
"signal": "pbiContainerWidth"
},
"height": {
"signal": "pbiContainerHeight"
},
"padding": 0,
"autosize": {
"type": "none",
"contains": "padding"
},
"config": {
"text": {
"font": "Segoe UI, Inter, -apple-system, Helvetica Neue, sans-serif"
}
},
"signals": [
{
"name": "LAYOUT_HeaderHeight",
"description": "Height of the category header strip on top of each category block, in px.",
"value": 22
},
{
"name": "LAYOUT_LegendHeight",
"description": "Height of the bottom row that holds the colour legend and the annotation, in px.",
"value": 36
},
{
"name": "LAYOUT_MapHeight",
"description": "Height left for the treemap once the bottom row is taken.",
"update": "max(60, height - LAYOUT_LegendHeight)"
},
{
"name": "UI_MarginMidpoint",
"description": "Margin that sets the middle stop of the colour scale: tiles above it go darker green.",
"value": 0.15
},
{
"name": "STATE_HoverCategory",
"description": "Category under the pointer: its frame is outlined and the other categories fade.",
"value": null,
"on": [
{
"events": "@leaf:pointerover, @catFrame:pointerover",
"update": "datum.Category"
},
{
"events": "@leaf:pointerout, @catFrame:pointerout",
"update": "null"
}
]
},
{
"name": "STATE_CrossFilter",
"description": "Click on a tile filters the report by its subcategory, a click on a category header by the whole category; a click elsewhere clears it.",
"value": [],
"on": [
{
"events": {
"source": "scope",
"type": "mouseup",
"markname": "leaf"
},
"update": "pbiCrossFilterApply(event, \"datum['__1__'] == '\" + datum.Item + \"'\")"
},
{
"events": {
"source": "scope",
"type": "mouseup",
"markname": "catFrame"
},
"update": "pbiCrossFilterApply(event, \"datum['__0__'] == '\" + datum.Category + \"'\")"
},
{
"events": {
"source": "view",
"type": "mouseup",
"filter": [
"!event.item || (event.item.mark.name != 'leaf' && event.item.mark.name != 'catFrame')"
]
},
"update": "pbiCrossFilterClear()"
}
]
}
],
"data": [
{
"name": "dataset"
},
{
"name": "legendSteps",
"values": [
{
"i": 0,
"m": -0.1
},
{
"i": 1,
"m": 0
},
{
"i": 2,
"m": 0.1
},
{
"i": 3,
"m": 0.2
},
{
"i": 4,
"m": 0.3
},
{
"i": 5,
"m": 0.4
}
]
},
{
"name": "rows",
"source": "dataset",
"transform": [
{
"type": "formula",
"as": "Category",
"expr": "datum['__0__']"
},
{
"type": "formula",
"as": "Item",
"expr": "datum['__1__']"
},
{
"type": "formula",
"as": "Sales",
"expr": "max(0, toNumber(datum['__2__']) || 0)"
},
{
"type": "formula",
"as": "Margin",
"expr": "toNumber(datum['__3__'])"
},
{
"type": "filter",
"expr": "datum.Sales > 0"
}
]
},
{
"name": "totals",
"source": "rows",
"transform": [
{
"type": "aggregate",
"ops": [
"sum"
],
"fields": [
"Sales"
],
"as": [
"grand"
]
}
]
},
{
"name": "catTotals",
"source": "rows",
"transform": [
{
"type": "aggregate",
"groupby": [
"Category"
],
"ops": [
"sum"
],
"fields": [
"Sales"
],
"as": [
"catSales"
]
}
]
},
{
"name": "tree",
"source": "rows",
"transform": [
{
"type": "nest",
"keys": [
"Category"
],
"generate": true
},
{
"type": "treemap",
"field": "Sales",
"sort": {
"field": "value",
"order": "descending"
},
"round": true,
"method": "squarify",
"ratio": 1.4,
"paddingInner": 3,
"paddingTop": {
"signal": "LAYOUT_HeaderHeight"
},
"size": [
{
"signal": "width"
},
{
"signal": "LAYOUT_MapHeight + LAYOUT_HeaderHeight"
}
]
}
]
},
{
"name": "cats",
"source": "tree",
"transform": [
{
"type": "filter",
"expr": "datum.depth === 1"
},
{
"type": "formula",
"as": "Category",
"expr": "datum.key"
},
{
"type": "lookup",
"from": "catTotals",
"key": "Category",
"fields": [
"Category"
],
"values": [
"catSales"
]
},
{
"type": "formula",
"as": "share",
"expr": "datum.catSales / data('totals')[0].grand"
},
{
"type": "formula",
"as": "w",
"expr": "datum.x1 - datum.x0"
}
]
},
{
"name": "leaves",
"source": "tree",
"transform": [
{
"type": "filter",
"expr": "!datum.children && datum.depth === 2"
},
{
"type": "formula",
"as": "w",
"expr": "datum.x1 - datum.x0"
},
{
"type": "formula",
"as": "h",
"expr": "datum.y1 - datum.y0"
},
{
"type": "formula",
"as": "share",
"expr": "datum.Sales / data('totals')[0].grand"
},
{
"type": "formula",
"as": "dark",
"expr": "datum.Margin < 0 || datum.Margin >= 0.27"
},
{
"type": "lookup",
"from": "catTotals",
"key": "Category",
"fields": [
"Category"
],
"values": [
"catSales"
]
},
{
"type": "formula",
"as": "ofCategory",
"expr": "datum.catSales ? datum.Sales / datum.catSales : 0"
}
]
},
{
"name": "worstMargin",
"source": "leaves",
"transform": [
{
"type": "window",
"sort": {
"field": "Margin",
"order": "ascending"
},
"ops": [
"row_number"
],
"as": [
"marginRank"
]
},
{
"type": "filter",
"expr": "datum.marginRank === 1"
}
]
}
],
"scales": [
{
"name": "color",
"type": "linear",
"domain": [
-0.1,
0,
{
"signal": "UI_MarginMidpoint"
},
0.4
],
"range": [
"#9f1d20",
"#f2c4bd",
"#d7ebe6",
"#0f6b5c"
],
"clamp": true,
"interpolate": "lab"
}
],
"marks": [
{
"type": "group",
"name": "map",
"encode": {
"update": {
"x": {
"value": 0
},
"y": {
"signal": "-LAYOUT_HeaderHeight"
},
"width": {
"signal": "width"
},
"height": {
"signal": "LAYOUT_MapHeight + LAYOUT_HeaderHeight"
}
}
},
"marks": [
{
"type": "rect",
"name": "catFrame",
"from": {
"data": "cats"
},
"encode": {
"update": {
"x": {
"field": "x0"
},
"y": {
"field": "y0"
},
"x2": {
"field": "x1"
},
"y2": {
"field": "y1"
},
"fill": {
"value": "#f4f5f7"
},
"stroke": {
"signal": "STATE_HoverCategory === datum.Category ? '#1f2933' : '#c8ccd2'"
},
"strokeWidth": {
"signal": "STATE_HoverCategory === datum.Category ? 2 : 1"
},
"cornerRadius": {
"value": 3
},
"cursor": {
"value": "pointer"
}
}
}
},
{
"type": "rect",
"name": "leaf",
"from": {
"data": "leaves"
},
"encode": {
"update": {
"x": {
"field": "x0"
},
"y": {
"field": "y0"
},
"x2": {
"field": "x1"
},
"y2": {
"field": "y1"
},
"fill": {
"scale": "color",
"field": "Margin"
},
"stroke": {
"value": "#ffffff"
},
"strokeWidth": {
"value": 1
},
"cornerRadius": {
"value": 2
},
"opacity": {
"signal": "datum.__selected__ === 'off' ? 0.3 : (STATE_HoverCategory && STATE_HoverCategory !== datum.Category ? 0.55 : 1)"
},
"cursor": {
"value": "pointer"
},
"tooltip": {
"signal": "{'title': datum.Item, 'Categoría': datum.Category, 'Ventas': pbiFormatAutoUnit(datum.Sales, '#,0.0'), '% del total': format(datum.share, '.1%'), 'Contribución a su categoría': format(datum.ofCategory, '.0%') + ' de ' + datum.Category, 'Margen': format(datum.Margin, '.1%')}"
}
}
}
},
{
"type": "text",
"name": "leafName",
"from": {
"data": "leaves"
},
"interactive": false,
"encode": {
"update": {
"x": {
"signal": "datum.x0 + 7"
},
"y": {
"signal": "datum.y0 + 16"
},
"text": {
"signal": "datum.w >= 74 && datum.h >= 34 ? datum.Item : ''"
},
"limit": {
"signal": "datum.w - 12"
},
"fontSize": {
"signal": "datum.w < 150 ? 11 : 12"
},
"fontWeight": {
"value": 600
},
"fill": {
"signal": "datum.dark ? '#ffffff' : '#1f2933'"
},
"opacity": {
"signal": "datum.__selected__ === 'off' ? 0.4 : 1"
}
}
}
},
{
"type": "text",
"name": "leafValue",
"from": {
"data": "leaves"
},
"interactive": false,
"encode": {
"update": {
"x": {
"signal": "datum.x0 + 7"
},
"y": {
"signal": "datum.y0 + 32"
},
"text": {
"signal": "datum.w >= 74 && datum.h >= 52 ? pbiFormatAutoUnit(datum.Sales, '#,0.0') + ' · ' + format(datum.share, '.0%') : ''"
},
"limit": {
"signal": "datum.w - 12"
},
"fontSize": {
"value": 11
},
"fill": {
"signal": "datum.dark ? '#ffffff' : '#3e4752'"
},
"opacity": {
"signal": "datum.__selected__ === 'off' ? 0.4 : 0.92"
}
}
}
},
{
"type": "text",
"name": "leafMargin",
"from": {
"data": "leaves"
},
"interactive": false,
"encode": {
"update": {
"x": {
"signal": "datum.x1 - 7"
},
"y": {
"signal": "datum.y1 - 8"
},
"align": {
"value": "right"
},
"text": {
"signal": "datum.w >= 74 && datum.h >= 72 ? 'margen ' + format(datum.Margin, '.0%') : ''"
},
"fontSize": {
"value": 11
},
"fontWeight": {
"signal": "datum.Margin < 0 ? 700 : 400"
},
"fill": {
"signal": "datum.dark ? '#ffffff' : '#3e4752'"
},
"opacity": {
"signal": "datum.__selected__ === 'off' ? 0.4 : 0.92"
}
}
}
},
{
"type": "text",
"name": "catLabel",
"from": {
"data": "cats"
},
"interactive": false,
"encode": {
"update": {
"x": {
"signal": "datum.x0 + 6"
},
"y": {
"signal": "datum.y0 + 15"
},
"text": {
"signal": "datum.w >= 60 ? upper(datum.Category) + ' ' + format(datum.share, '.0%') : ''"
},
"limit": {
"signal": "datum.w - 10"
},
"fontSize": {
"value": 11
},
"fontWeight": {
"value": 700
},
"fill": {
"value": "#2f3a45"
}
}
}
}
]
},
{
"type": "group",
"name": "legend",
"encode": {
"update": {
"x": {
"signal": "width - 186"
},
"y": {
"signal": "height - LAYOUT_LegendHeight + 8"
}
}
},
"marks": [
{
"type": "text",
"encode": {
"update": {
"x": {
"value": -10
},
"y": {
"value": 9
},
"align": {
"value": "right"
},
"text": {
"value": "Margen"
},
"fontSize": {
"value": 11
},
"fill": {
"value": "#5b6672"
}
}
}
},
{
"type": "rect",
"from": {
"data": "legendSteps"
},
"encode": {
"update": {
"x": {
"signal": "datum.i * 30"
},
"width": {
"value": 29
},
"y": {
"value": 0
},
"height": {
"value": 12
},
"fill": {
"scale": "color",
"field": "m"
}
}
}
},
{
"type": "text",
"from": {
"data": "legendSteps"
},
"encode": {
"update": {
"x": {
"signal": "datum.i * 30 + 14.5"
},
"y": {
"value": 23
},
"align": {
"value": "center"
},
"text": {
"signal": "format(datum.m, '.0%')"
},
"fontSize": {
"value": 10
},
"fill": {
"value": "#5b6672"
}
}
}
}
]
},
{
"type": "text",
"name": "annotationWorstMargin",
"from": {
"data": "worstMargin"
},
"interactive": false,
"encode": {
"update": {
"x": {
"value": 0
},
"y": {
"signal": "height - LAYOUT_LegendHeight + 18"
},
"baseline": {
"value": "middle"
},
"text": {
"signal": "'Peor margen: ' + datum.Item + ' · ' + format(datum.Margin, '.0%') + ' con el ' + format(datum.share, '.0%') + ' de la venta'"
},
"limit": {
"signal": "width - 230"
},
"fontSize": {
"value": 12
},
"fontStyle": {
"value": "italic"
},
"fill": {
"value": "#5b6672"
}
}
}
}
]
}