Autowidth Bar Right Aligned Labels

Requires a DAX Measure to return highest value of all categories used to position labels to the right

Max all categories (DAX) = CALCULATE (MAXX (DISTINCT ( ‘Table'[Category] ),CALCULATE ( SUM ( ‘Table'[Measure] ) ) ),ALLSELECTED ( ‘Table ))

Change colours with HEX or CSS colours :

{
  "data": {"name": "dataset"},
  "height": {"step": 35},
  "encoding": {
    "y": {
      "field": "Page",
      "type": "nominal",
      "sort": {
        "op": "sum",
        "field": "Pageviews",
        "order": "descending"
      },
      "title": null,
      "axis": {
        "bandPosition": 0,
        "grid": false,
        "domain": false,
        "ticks": false,
        "labelAlign": "left",
        "labelBaseline": "middle",
        "labelPadding": -1,
        "labelOffset": -15,
        "titleX": 5,
        "titleY": -5,
        "titleAngle": 0,
        "titleAlign": "left",
        "zindex": 1,
        "blend": "luminosity",
        "labelColor": {
          "expr": "luminance ( scale ( 'color', datum['Pageviews'] ) ) > 0.5 ? 'white' : 'black'"
        }
      }
    }
  },
  "layer": [
    {
      "mark": {
        "type": "bar",
        "cornerRadiusEnd": 4,
        "height": {"band": 0.5},
        "tooltip": true
      },
      "encoding": {
        "x": {
          "field": "Pageviews",
          "type": "quantitative",
          "title": null,
          "axis": null
        },
        "color": {
          "scale": {
            "range": [
              "Yellow",
              "Navy"
            ]
          },
          "legend": null,
          "field": "Pageviews",
          "type": "quantitative",
          "title": ""
        },
        "opacity": {
          "condition": {
            "test": {
              "field": "__selected__",
              "equal": "off"
            },
            "value": 0.3
          }
        }
      }
    },
    {
      "mark": {
        "type": "text",
        "align": "left",
        "xOffset": 10,
        "x": "width",
        "fontWeight": "Bold",
        "aria": false
      },
      "encoding": {
        "text": {
          "field": "Pageviews",
          "format": ",.0f"
        },
        "x": {
          "field": "Max All",
          "type": "quantitative",
          "title": null,
          "axis": null
        }
      }
    }
  ]
}

Leave a comment

Your email address will not be published. Required fields are marked *