- Inicio
- Recursos
- Galería Deneb
- Barras de ventas y margen por categoría y subcategoría
Barras de ventas y margen por categoría y subcategoría
¿Qué categorías venden más y qué subcategorías dentro de ellas venden sin dejar dinero? Cada barra es una categoría, de mayor a menor venta, partida en sus subcategorías: verde si ganan dinero (más oscuro, más margen) y rojo si lo pierden. En Contoso salta Video Game Consoles: la segunda subcategoría que más vende y la única que pierde, −4,1 % de margen.
💡 Cuándo usarlo
Cuando la pregunta es «quién vende más y quién no gana» en una jerarquía de dos niveles y el orden importa: las longitudes se comparan mejor que las áreas. Funciona bien con pocas categorías (hasta unas 8) y pocas subcategorías por barra; con muchas piezas pequeñas, el treemap de la misma pregunta las reparte mejor.
La misma pregunta respondida con un treemap: área por venta y color por margen →
Vista previa en vivo
Render con datos de muestra · Vega/Vega-Lite🖱️ Pasa el cursor por un segmento: se resalta y el tooltip añade su peso en la categoría y en el total, el margen bruto y su puesto en ventas. El clic filtra el resto del informe por esa subcategoría (en el nombre de la categoría, por la categoría entera); aquí atenúa las demás piezas, porque 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 6.4.0
- Transforms
- aggregate agregación, filter filtro, formula fórmula calculada, joinaggregate agregación por grupo, stack apilado, window ventana (acumulados/ranking)
- Parámetros
-
-
UI_MarginFullGreen: margen en el que un segmento que gana llega al verde más oscuro; por debajo, el verde se aclara hacia el 0 % se cambia en el spec · por defecto 0.4
Y 10 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 -
pbiFormat: aplica el formato de número o fecha de Power BI a un valor
-
🛠️ Cómo está hecho
Vega puro: una escala band ordena las categorías por venta y el transform stack apila sus subcategorías de mayor a menor dentro de cada barra. El color sale del signo del margen: rojo si pierde, y verde cuya intensidad sube con el margen % si gana. El color no es el único canal: la cifra lleva ▲ o ▼ y la subcategoría que pierde va en negrita. Un borde blanco separa los segmentos; el nombre y la cifra salen solo donde caben y el resto se lee en el tooltip. Al final de cada barra van el total de la categoría y su margen %, calculado como margen bruto entre venta, no como media de porcentajes. Al pasar el cursor se resalta el segmento; el clic filtra el informe por esa subcategoría y el clic en el nombre de la categoría, por la categoría entera. La vista previa usa las 4 categorías y 14 subcategorías de Contoso Retail 2023–2024, las mismas del paquete.
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/v6.json",
"description": "Una barra por categoría, ordenadas por venta y partidas en sus subcategorías, cada segmento coloreado por el signo de su margen: verde si gana dinero, rojo si lo pierde. Responde qué categorías venden más y qué subcategorías dentro de ellas venden sin dejar dinero. Por CSalcedoDataBI · https://csalcedodatabi.com/deneb/barras-ventas-margen-subcategoria",
"usermeta": {
"deneb": {
"build": "2.0.1.0",
"metaVersion": 2,
"provider": "vega",
"providerVersion": "6.4.0"
},
"interactivity": {
"tooltip": true,
"contextMenu": true,
"selection": true,
"selectionMode": "advanced",
"highlight": false,
"dataPointLimit": 50
},
"information": {
"name": "Barras de ventas y margen por categoría",
"description": "One bar per category, sorted by sales and stacked by subcategory, each segment coloured by the sign of its margin (green earns, darker with more margin; red loses), with the category total and margin at the end of each bar. Ficha y vista previa en vivo: https://csalcedodatabi.com/deneb/barras-ventas-margen-subcategoria. Autor: Cristobal Salcedo Beltrán.",
"author": "Cristobal Salcedo Beltrán",
"uuid": "6f3c2b8e-4d1a-4c57-9b0e-2a7d5e8f1c34",
"generated": "2026-12-03T22:00:00.000Z",
"previewImageBase64PNG": ""
},
"config": "{}",
"datasets": {
"dataset": [
{
"key": "__dataset.0__",
"name": "CategoryName",
"description": "Primer nivel: una barra por valor (categoría, región, familia…).",
"type": "text",
"kind": "column",
"supportFieldConfiguration": {
"highlight": false,
"highlightStatus": false,
"highlightComparator": false,
"format": false,
"formatted": false,
"names": false
}
},
{
"key": "__dataset.1__",
"name": "SubCategoryName",
"description": "Segundo nivel: un segmento por valor dentro de su barra (subcategoría, producto, tienda…).",
"type": "text",
"kind": "column",
"supportFieldConfiguration": {
"highlight": false,
"highlightStatus": false,
"highlightComparator": false,
"format": false,
"formatted": false,
"names": false
}
},
{
"key": "__dataset.2__",
"name": "Total Sales",
"description": "Medida que da la longitud de cada segmento y el orden. Debe ser positiva.",
"type": "numeric",
"kind": "measure",
"supportFieldConfiguration": {
"highlight": false,
"highlightStatus": false,
"highlightComparator": false,
"format": true,
"formatted": false,
"names": false
}
},
{
"key": "__dataset.3__",
"name": "Margin %",
"description": "Ratio cuyo signo da el color (rojo por debajo de 0) y cuyo valor da la intensidad del verde, hasta el 40 %.",
"type": "numeric",
"kind": "measure",
"supportFieldConfiguration": {
"highlight": false,
"highlightStatus": false,
"highlightComparator": false,
"format": true,
"formatted": false,
"names": false
}
}
]
}
},
"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 top strip with the heading of the totals column, in px.",
"value": 20
},
{
"name": "LAYOUT_FooterHeight",
"description": "Height of the bottom row with the legend and the annotation, in px.",
"value": 34
},
{
"name": "LAYOUT_NameWidth",
"description": "Width of the left column with the category names, in px.",
"update": "clamp(width * 0.2, 90, 190)"
},
{
"name": "LAYOUT_TotalWidth",
"description": "Width of the right column with each category total and margin, in px.",
"value": 92
},
{
"name": "LAYOUT_PlotWidth",
"description": "Width left for the bars once both columns are taken.",
"update": "max(40, width - LAYOUT_NameWidth - LAYOUT_TotalWidth - 12)"
},
{
"name": "LAYOUT_PlotHeight",
"description": "Height left for the bars once the header and the footer are taken.",
"update": "max(40, height - LAYOUT_HeaderHeight - LAYOUT_FooterHeight)"
},
{
"name": "LAYOUT_MinLabelWidth",
"description": "Narrowest segment, in px, that shows a label; a label also needs its estimated text width, or it is read in the tooltip.",
"value": 64
},
{
"name": "LAYOUT_CharWidth",
"description": "Average width of one character of a segment label, in px: a name shows only when it fits whole.",
"value": 6.2
},
{
"name": "UI_MarginFullGreen",
"description": "Margin at which a winning segment reaches the darkest green; below it the green fades towards 0 %.",
"value": 0.4
},
{
"name": "STATE_Hover",
"description": "Segment under the pointer: the other segments fade.",
"value": null,
"on": [
{
"events": "@segment:pointerover",
"update": "datum.Item"
},
{
"events": "@segment:pointerout",
"update": "null"
}
]
},
{
"name": "STATE_CrossFilter",
"description": "Click on a segment filters the report by its subcategory, a click on a category name by the whole category; a click elsewhere clears it.",
"value": [],
"on": [
{
"events": {
"source": "scope",
"type": "mouseup",
"markname": "segment"
},
"update": "pbiCrossFilterApply(event, \"datum['__dataset.1__'] == '\" + datum.Item + \"'\")"
},
{
"events": {
"source": "scope",
"type": "mouseup",
"markname": "catName"
},
"update": "pbiCrossFilterApply(event, \"datum['__dataset.0__'] == '\" + datum.Category + \"'\")"
},
{
"events": {
"source": "view",
"type": "mouseup",
"filter": [
"!event.item || (event.item.mark.name != 'segment' && event.item.mark.name != 'catName')"
]
},
"update": "pbiCrossFilterClear()"
}
]
}
],
"data": [
{
"name": "dataset"
},
{
"name": "rows",
"source": "dataset",
"transform": [
{
"type": "formula",
"as": "Category",
"expr": "datum['__dataset.0__']"
},
{
"type": "formula",
"as": "Item",
"expr": "datum['__dataset.1__']"
},
{
"type": "formula",
"as": "Sales",
"expr": "toNumber(datum['__dataset.2__'])"
},
{
"type": "formula",
"as": "Margin",
"expr": "toNumber(datum['__dataset.3__'])"
},
{
"type": "filter",
"expr": "isValid(datum.Sales) && isFinite(datum.Sales) && datum.Sales > 0 && isValid(datum.Margin) && isFinite(datum.Margin)"
},
{
"type": "formula",
"as": "SalesFormat",
"expr": "isValid(datum['__dataset.2____format']) && datum['__dataset.2____format'] != '' ? datum['__dataset.2____format'] : '$#,0'"
},
{
"type": "formula",
"as": "Loss",
"expr": "datum.Margin < 0"
},
{
"type": "formula",
"as": "GrossMargin",
"expr": "datum.Sales * datum.Margin"
},
{
"type": "joinaggregate",
"fields": [
"Sales",
"Sales"
],
"ops": [
"sum",
"count"
],
"as": [
"Total",
"N"
]
},
{
"type": "joinaggregate",
"groupby": [
"Category"
],
"fields": [
"Sales"
],
"ops": [
"sum"
],
"as": [
"CatSales"
]
},
{
"type": "window",
"sort": {
"field": "Sales",
"order": "descending"
},
"ops": [
"row_number"
],
"as": [
"Rank"
]
},
{
"type": "stack",
"groupby": [
"Category"
],
"field": "Sales",
"sort": {
"field": "Sales",
"order": "descending"
},
"as": [
"s0",
"s1"
]
},
{
"type": "formula",
"as": "Share",
"expr": "datum.Sales / datum.Total"
},
{
"type": "formula",
"as": "OfCategory",
"expr": "datum.Sales / datum.CatSales"
},
{
"type": "formula",
"as": "SalesLabel",
"expr": "datum.Sales >= 1e6 ? '$' + format(datum.Sales / 1e6, '.1f') + ' M' : datum.Sales >= 1e3 ? '$' + format(datum.Sales / 1e3, '.0f') + ' K' : '$' + format(datum.Sales, ',.0f')"
},
{
"type": "formula",
"as": "MarginLabel",
"expr": "(datum.Loss ? '▼ ' : '▲ ') + format(datum.Margin, '.1%')"
},
{
"type": "formula",
"as": "NameWidth",
"expr": "(length(datum.Item) + (datum.Loss ? 2 : 0)) * LAYOUT_CharWidth + 14"
},
{
"type": "formula",
"as": "ValueWidth",
"expr": "(length(datum.SalesLabel) + 9) * LAYOUT_CharWidth * 0.92 + 14"
},
{
"type": "formula",
"as": "Dark",
"expr": "datum.Loss || datum.Margin >= UI_MarginFullGreen * 0.45"
}
]
},
{
"name": "cats",
"source": "rows",
"transform": [
{
"type": "aggregate",
"groupby": [
"Category"
],
"fields": [
"Sales",
"GrossMargin",
"Item"
],
"ops": [
"sum",
"sum",
"count"
],
"as": [
"CatSales",
"CatGross",
"Pieces"
]
},
{
"type": "formula",
"as": "CatMargin",
"expr": "datum.CatGross / datum.CatSales"
},
{
"type": "formula",
"as": "CatSalesLabel",
"expr": "datum.CatSales >= 1e6 ? '$' + format(datum.CatSales / 1e6, '.1f') + ' M' : '$' + format(datum.CatSales / 1e3, '.0f') + ' K'"
},
{
"type": "formula",
"as": "CatMarginLabel",
"expr": "(datum.CatMargin < 0 ? '▼ ' : '▲ ') + format(datum.CatMargin, '.1%')"
}
]
},
{
"name": "losers",
"source": "rows",
"transform": [
{
"type": "filter",
"expr": "datum.Loss"
},
{
"type": "joinaggregate",
"fields": [
"Item"
],
"ops": [
"count"
],
"as": [
"LossCount"
]
},
{
"type": "window",
"sort": {
"field": "Sales",
"order": "descending"
},
"ops": [
"row_number"
],
"as": [
"LossRank"
]
},
{
"type": "filter",
"expr": "datum.LossRank === 1"
}
]
},
{
"name": "legendGreens",
"values": [
{
"i": 0,
"f": 0.05
},
{
"i": 1,
"f": 0.3
},
{
"i": 2,
"f": 0.55
},
{
"i": 3,
"f": 0.8
},
{
"i": 4,
"f": 1
}
]
},
{
"name": "emptyState",
"values": [
{
"text": "Sin datos para la selección actual"
}
],
"transform": [
{
"type": "filter",
"expr": "length(data('rows')) === 0"
}
]
}
],
"scales": [
{
"name": "y",
"type": "band",
"domain": {
"data": "cats",
"field": "Category",
"sort": {
"field": "CatSales",
"op": "max",
"order": "descending"
}
},
"range": [
0,
{
"signal": "LAYOUT_PlotHeight"
}
],
"paddingInner": 0.32,
"paddingOuter": 0.12
},
{
"name": "x",
"type": "linear",
"domain": {
"data": "cats",
"field": "CatSales"
},
"zero": true,
"nice": false,
"range": [
0,
{
"signal": "LAYOUT_PlotWidth"
}
]
},
{
"name": "green",
"type": "linear",
"domain": [
0,
{
"signal": "UI_MarginFullGreen"
}
],
"range": [
"#c6e7d1",
"#166534"
],
"clamp": true,
"interpolate": "lab"
}
],
"marks": [
{
"type": "group",
"name": "plot",
"encode": {
"update": {
"x": {
"signal": "LAYOUT_NameWidth"
},
"y": {
"signal": "LAYOUT_HeaderHeight"
},
"width": {
"signal": "LAYOUT_PlotWidth"
},
"height": {
"signal": "LAYOUT_PlotHeight"
}
}
},
"marks": [
{
"type": "rect",
"name": "segment",
"from": {
"data": "rows"
},
"encode": {
"update": {
"x": {
"scale": "x",
"field": "s0"
},
"x2": {
"scale": "x",
"field": "s1"
},
"y": {
"scale": "y",
"field": "Category"
},
"height": {
"scale": "y",
"band": 1
},
"fill": {
"signal": "datum.Loss ? '#B91C1C' : scale('green', datum.Margin)"
},
"stroke": {
"value": "#ffffff"
},
"strokeWidth": {
"value": 1.5
},
"opacity": {
"signal": "datum.__selected__ === 'off' ? 0.3 : (STATE_Hover && STATE_Hover !== datum.Item ? 0.45 : 1)"
},
"cursor": {
"value": "pointer"
},
"tooltip": {
"signal": "{'title': datum.Item, 'Categoría': datum.Category, 'Ventas': pbiFormat(datum.Sales, datum.SalesFormat), '% de su categoría': format(datum.OfCategory, '.1%'), '% del total': format(datum.Share, '.1%'), 'Margen': format(datum.Margin, '.1%'), 'Margen bruto': pbiFormat(datum.GrossMargin, datum.SalesFormat), 'Puesto por ventas': datum.Rank + ' de ' + datum.N + ' subcategorías'}"
}
}
}
},
{
"type": "text",
"name": "segmentName",
"from": {
"data": "rows"
},
"interactive": false,
"encode": {
"update": {
"x": {
"signal": "scale('x', datum.s0) + 7"
},
"y": {
"signal": "scale('y', datum.Category) + bandwidth('y') / 2 - (bandwidth('y') >= 40 ? 8 : 0)"
},
"baseline": {
"value": "middle"
},
"text": {
"signal": "scale('x', datum.s1) - scale('x', datum.s0) >= max(LAYOUT_MinLabelWidth, datum.NameWidth) && bandwidth('y') >= 22 ? (datum.Loss ? '▼ ' : '') + datum.Item : ''"
},
"limit": {
"signal": "scale('x', datum.s1) - scale('x', datum.s0) - 12"
},
"fontSize": {
"value": 11
},
"fontWeight": {
"signal": "datum.Loss ? 700 : 600"
},
"fill": {
"signal": "datum.Dark ? '#ffffff' : '#1f2933'"
},
"opacity": {
"signal": "datum.__selected__ === 'off' ? 0.45 : 1"
}
}
}
},
{
"type": "text",
"name": "segmentValue",
"from": {
"data": "rows"
},
"interactive": false,
"encode": {
"update": {
"x": {
"signal": "scale('x', datum.s0) + 7"
},
"y": {
"signal": "scale('y', datum.Category) + bandwidth('y') / 2 + 9"
},
"baseline": {
"value": "middle"
},
"text": {
"signal": "scale('x', datum.s1) - scale('x', datum.s0) >= max(LAYOUT_MinLabelWidth, datum.ValueWidth) && bandwidth('y') >= 40 ? datum.SalesLabel + ' · ' + (datum.Loss ? '▼ ' : '▲ ') + format(datum.Margin, '.0%') : ''"
},
"limit": {
"signal": "scale('x', datum.s1) - scale('x', datum.s0) - 12"
},
"fontSize": {
"value": 10
},
"fill": {
"signal": "datum.Dark ? '#ffffff' : '#3e4752'"
},
"opacity": {
"signal": "datum.__selected__ === 'off' ? 0.45 : 0.95"
}
}
}
},
{
"type": "text",
"name": "catName",
"from": {
"data": "cats"
},
"encode": {
"update": {
"x": {
"value": -10
},
"y": {
"scale": "y",
"field": "Category",
"band": 0.5
},
"align": {
"value": "right"
},
"baseline": {
"value": "middle"
},
"text": {
"field": "Category"
},
"limit": {
"signal": "LAYOUT_NameWidth - 14"
},
"fontSize": {
"value": 12
},
"fontWeight": {
"value": 600
},
"fill": {
"value": "#1f2933"
},
"cursor": {
"value": "pointer"
},
"tooltip": {
"signal": "{'title': datum.Category, 'Ventas': pbiFormat(datum.CatSales, '$#,0'), 'Margen': format(datum.CatMargin, '.1%'), 'Subcategorías': datum.Pieces}"
}
}
}
},
{
"type": "text",
"name": "catTotal",
"from": {
"data": "cats"
},
"interactive": false,
"encode": {
"update": {
"x": {
"signal": "scale('x', datum.CatSales) + 8"
},
"y": {
"signal": "scale('y', datum.Category) + bandwidth('y') / 2 - (bandwidth('y') >= 34 ? 7 : 0)"
},
"baseline": {
"value": "middle"
},
"text": {
"signal": "bandwidth('y') >= 34 ? datum.CatSalesLabel : datum.CatSalesLabel + ' ' + datum.CatMarginLabel"
},
"fontSize": {
"value": 12
},
"fontWeight": {
"value": 700
},
"fill": {
"value": "#1f2933"
}
}
}
},
{
"type": "text",
"name": "catMargin",
"from": {
"data": "cats"
},
"interactive": false,
"encode": {
"update": {
"x": {
"signal": "scale('x', datum.CatSales) + 8"
},
"y": {
"signal": "scale('y', datum.Category) + bandwidth('y') / 2 + 9"
},
"baseline": {
"value": "middle"
},
"text": {
"signal": "bandwidth('y') >= 34 ? datum.CatMarginLabel + ' margen' : ''"
},
"fontSize": {
"value": 11
},
"fill": {
"signal": "datum.CatMargin < 0 ? '#B91C1C' : '#166534'"
}
}
}
},
{
"type": "text",
"name": "headTotal",
"interactive": false,
"encode": {
"update": {
"x": {
"signal": "LAYOUT_PlotWidth + 8"
},
"y": {
"value": -6
},
"text": {
"value": "Total y margen"
},
"fontSize": {
"value": 10
},
"fontWeight": {
"value": 600
},
"fill": {
"value": "#5b6672"
}
}
}
}
]
},
{
"type": "group",
"name": "legend",
"encode": {
"update": {
"x": {
"signal": "width - 262"
},
"y": {
"signal": "height - LAYOUT_FooterHeight + 12"
}
}
},
"marks": [
{
"type": "rect",
"encode": {
"update": {
"x": {
"value": 0
},
"y": {
"value": 0
},
"width": {
"value": 12
},
"height": {
"value": 10
},
"cornerRadius": {
"value": 2
},
"fill": {
"value": "#B91C1C"
}
}
}
},
{
"type": "text",
"encode": {
"update": {
"x": {
"value": 17
},
"y": {
"value": 5
},
"baseline": {
"value": "middle"
},
"text": {
"value": "▼ Pierde"
},
"fontSize": {
"value": 11
},
"fill": {
"value": "#3e4752"
}
}
}
},
{
"type": "rect",
"from": {
"data": "legendGreens"
},
"encode": {
"update": {
"x": {
"signal": "78 + datum.i * 13"
},
"y": {
"value": 0
},
"width": {
"value": 12
},
"height": {
"value": 10
},
"fill": {
"signal": "scale('green', datum.f * UI_MarginFullGreen)"
}
}
}
},
{
"type": "text",
"encode": {
"update": {
"x": {
"value": 147
},
"y": {
"value": 5
},
"baseline": {
"value": "middle"
},
"text": {
"signal": "'▲ Gana: 0 % → ' + format(UI_MarginFullGreen, '.0%')"
},
"fontSize": {
"value": 11
},
"fill": {
"value": "#3e4752"
}
}
}
}
]
},
{
"type": "text",
"name": "annotationLosers",
"from": {
"data": "losers"
},
"interactive": false,
"encode": {
"update": {
"x": {
"value": 0
},
"y": {
"signal": "height - LAYOUT_FooterHeight + 17"
},
"baseline": {
"value": "middle"
},
"text": {
"signal": "datum.LossCount + ' de ' + datum.N + (datum.LossCount === 1 ? ' pierde dinero: ' : ' pierden; la que más vende: ') + datum.Item + ', n.º ' + datum.Rank + ' en ventas'"
},
"limit": {
"signal": "width - 280"
},
"fontSize": {
"value": 12
},
"fontStyle": {
"value": "italic"
},
"fill": {
"value": "#3e4752"
}
}
}
},
{
"type": "text",
"name": "emptyMessage",
"from": {
"data": "emptyState"
},
"interactive": false,
"encode": {
"update": {
"x": {
"signal": "width / 2"
},
"y": {
"signal": "height / 2"
},
"align": {
"value": "center"
},
"baseline": {
"value": "middle"
},
"text": {
"field": "text"
},
"fontSize": {
"value": 13
},
"fill": {
"value": "#5b6672"
}
}
}
}
]
}