StatCan / dataviz-components

Data visualizations components made with D3.js
Other
6 stars 3 forks source link

Label scatterChart circles #8

Open KatiRG opened 5 years ago

KatiRG commented 5 years ago

I'm thinking of contributing a modification to scatterChart to allow text labels to be appended to circles. In the current form, the circles are not grouped under a g node and therefore it is not possible to add any text. In my modified form, I define scatterGroups with an appended g that the circles are then attached to, and with a small addition of code, the text can be appended under the same g. I use cx and cy to determine the position of the text. The text itself comes from z.getNames in the settings file:

  z: {
    label: i18next.t("z_label", {ns: "scatter"}),
    getNames: function(d) {
      return i18next.t(d.id, {ns: "scatter"});
    },

So here is the modified scatter.js code:

const scatterGroups = scatter
        .enter()
        .append("g");

      scatterGroups
        .append("circle")
          .attr("r", pRadius)
          .attr("id", idFn)
          .attr("class", classFn)
          .attr("cx", xFn)
          .attr("cy", yFn);

      scatterGroups
          .append("text")
          .attr("class", "point-text")
          .attr("dx", "1em")
          .attr("dy", "0.35em")
          // .attr("x", 7)
          .attr("x", function(d) {
            return d3.select(`#${d.id}`).attr("cx");
          })
          .attr("y", function(d) {
            return d3.select(`#${d.id}`).attr("cy");
          })
          .text(function(d) {
            return sett.z.getNames(d);
          });

      scatterGroups
        .transition(transition)
        .attr("class", classFn)
        .attr("cx", xFn)
        .attr("cy", yFn);

      scatterGroups
        .exit()
          .remove();

Which creates this dom:

<g class="point point1 visible cx="12 cy="12">
  <circle r="12" id="NYC" class="point point1 visible" fill="#7a0177" cx="12" cy="12"></circle>
  <text class="point-text" dx="1em" dy="0.35em" x="12" y="12">New York City</text>
</g>
LaurentGoderre commented 5 years ago

There's already a way to add labels:

https://github.com/StatCan/dataviz-components/blob/master/src/scatter/demo.js#L37-L39 https://github.com/StatCan/dataviz-components/blob/master/src/scatter/scatter.js#L174

KatiRG commented 5 years ago

Excellent! I have used that then. I guess it is not important for the circle and text to be under the same g node. I normally see it done like that (like mbostock here https://observablehq.com/@d3/scatterplot) but this works fine too! Thanks

LaurentGoderre commented 5 years ago

The problem with that is that some text would be under some dots. It used to be like that but was switch to the current way.