Positionning text depending on increase or decrease of population in bar chart

Hi everyone,

Pretty new to javascript, d3, and observable, but bear with me. Coming from a GIS/scientific computing background. Starting to love d3 to create beautiful graphs with a lot less effort. ObservableHQ notebooks seem really familiar coming from Jupyter notebooks.

I am working on creating some bar plots of the 2021 Census data. In the last graph of the published notebook here, I am trying to get the dx to depend on d. More precisely, for negative population variations, I would like the text to appear on the right of the bar and, for positive population variations, on the left.

The syntax dx: d => getTextPosition(d.variation_population_2021_2016, 10) is not working. Is it because d is not accessible for this specific tag. No specific error message is raised and I have not been able to find similar issues or mentions in the documentation.

Thanks,

Zac

At present dx is a constant, not available as a channel. What you might want to do in this case is to use two marks, with a filter for positive/negative values:

    Plot.text(
      economicRegionData, {x: "variation_population_2021_2016", y: "cmaname",
                           filter: d => d.variation_population_2021_2016 >= 0,
                           text: d => (d.variation_population_2021_2016*100).toFixed(1), 
                           textAnchor: "start",
                           dx: 5,
                           fontSize: 11
                          }
    ),
    Plot.text(
      economicRegionData, {x: "variation_population_2021_2016", y: "cmaname",
                           filter: d => d.variation_population_2021_2016 < 0,
                           text: d => (d.variation_population_2021_2016*100).toFixed(1), 
                           textAnchor: "end",
                           dx: -5,
                           fontSize: 11
                          }
    ),
1 Like

Exactly what I needed! thanks

1 Like

It could be another question of itself, but it still relates to the labels. In the republished notebook, the maximum negative values actually overlap the place names. I’ve been scrambling everywhere to find how to add some white space to the text or change the position of the axis to no avail. Do you have an idea @Fil of how I could work this out?

you could use an inset for the x scale, for example:

x: { insetLeft: 25, … }