viewof bail_race_selection = Inputs.select(
  transpose(bail_selector_values), {
    'format': (entry) => {
      return entry['race_defendant']
    },
    'keyof': (entry) => {
      return entry['race_defendant']
    },
    'valueof': (entry) => {
      return entry['race_defendant']
    },
    'label': 'Defendant race', 
    'value': 'ALL'
  }
)
filtered_bail = transpose(combined_bail_dataset).filter((row) => {
  return row['race_defendant'] == bail_race_selection
})

percentageFormat = function(n) {
  return Intl.NumberFormat('en-US', {
      style: "percent",
      minimumFractionDigits: 0,
      maximumFractionDigits: 1
  }).format(n);
}
bail_history_plot = Plot.plot({
  caption: combined_dataset_caption,
  x: {
    tickFormat: (r) => {
      return r
    },
    label: 'arrest year'
  },
  y: {
    tickFormat: (r) => {
      return r * 100
    },
    label: '%',
  },
  marks: [
    Plot.barY(filtered_bail, 
      Plot.stackY({
        x: (r) => {
          return r['arrest_year']
        },
        y: (r) => {
          return r['pct_by_bin']
        }, 
        fill: 'bin',
        sort: (v) => {
          return v['bin_val']
        }
      })
    ),
    Plot.textY(filtered_bail, 
      Plot.stackY({
        text: (r) => {
          return percentageFormat(r['pct_by_bin'])
        },
        y: (r) => {
          return r['pct_by_bin'] 
        },
        x: 'arrest_year'
      })
    ),
    Plot.ruleY([0]),
  ],
  color: {
    domain: bail_amount_labels,
    range: bail_color_palette,
  }
})

bail_history_plot.legend('color', {
  columns: 1,
  label: 'Bail Amount in $',
})