{
  "$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"
          }
        }
      }
    }
  ]
}