FormidableLabs / victory

A collection of composable React components for building interactive data visualizations
http://commerce.nearform.com/open-source/victory/
Other
10.96k stars 525 forks source link

VictoryPie curved text labels #405

Open InsidersByte opened 7 years ago

InsidersByte commented 7 years ago

I would like to have curved text labels on a pie chart. I spoke both @boygirl and Jani about this at a recent meetup.

I am more than happy to contribute, but as I mentioned I am not sure how best this would fit in.

I created a pen that shows a basic example of this.

The most important bit is this snippet which creates the segments.

const segments = (pie(data)).map((d, i) => (
  <g key={i}>
    <path fill={colours(i)} d={segmentArc(d)} />
    <path d={textArc(d)} id={`${id}-${i}`} />
    <text style={styles.label}>
      <textPath startOffset="25%" xlinkHref={`${window.location.href.replace(window.location.hash, "")}#${id}-${i}`}>
        {d.data.name}
      </textPath>
    </text>
  </g>
 ));

One thing to note is that I had to figure out was how to get this to work when you have HTML5 based navigation. I originally had xlinkHref={#${id}-${i}} and it worked fine with hashbang navigation, but broke when used with HTML5 based navigation.

I am not an SVG wiz so not sure if there is a better way to fix it, but I ended up having to prepend ${window.location.href.replace(window.location.hash, "")} to the xlinkHref. (see here)

screen shot 2016-10-24 at 11 53 04 (example pie chart)

This tutorial helped me understand how to place text on an arc http://www.visualcinnamon.com/2015/09/placing-text-on-arcs.html

boygirl commented 7 years ago

@InsidersByte Thanks! I think we can get this done by creating some curved label primitive that renders a path or arc in a <defs> and then references it in the textPath. We're already calculating a label radius, so it shouldn't be a lot of work to calculate an arc or path to pass to the curved label. Also, I was doing a tiny bit of reading on the <defs> spec, and I think it may potentially solve your HTML5 nav problem https://www.w3.org/TR/SVG/struct.html#Head

InsidersByte commented 7 years ago

@boygirl thanks, using <defs> did solve the base tag problem 👍 (http://codepen.io/insidersbyte/pen/pEYAPa?editors=0010)