Howdy, Stranger!

We are about to switch to a new forum software. Until then we have removed the registration on this forum.

Hover over pie chart segment and show the array value associated

edited November 2015

I created a pie chart and the sizes of the segments are based off of values in an array. I can't seem to figure out how I can hover over the specific segment and show the corresponding array value.

Can anyone point me in the right direction?

Tagged:

You can use atan2() to get the angle of the mouse in relation to a point.
The implementation would depend on the way how you draw your pie-chart. Here is an example:

``````float[] values = {30, 100, 20};
int[] colors = {#880000, #008800, #000088};

void setup() {
size(300, 300);
}

void draw() {
background(255);
pieChart(width/2, height/2, 200, values, colors);
}

/*
pX, pY : position
pVal: Array of Values
pCols: Array of colors
*/
void pieChart(float pX, float pY, float pDia, float[] pVal, int[]pCols) {
noStroke();
float total = 0;
float lastAngle= -PI;
float mouseAngle = atan2(mouseY-pY, mouseX-pX);

// get sum of values
for (int i =0; i<pVal.length; i++) {
total += pVal[i];
}

for (int i =0; i<pVal.length; i++) {
fill(pCols[i]);
float angle = map(pVal[i], 0, total, 0, 2*PI);
arc(pX, pY, pDia, pDia, lastAngle, lastAngle+angle, PIE);

if ( mouseAngle >= lastAngle && mouseAngle < lastAngle+angle ) {
text(values[i], pX-pDia/2,pY-pDia/2);
}

lastAngle += angle;
}
}
``````
• That's a great answer. Thanks for taking the time.

• An alternative approach involves creating a separate buffer image that uses the array index as a colour applied to hit areas. You can then just do a get() at the equivalent location in your buffer to determine the index of the element to retrieve from the array. Here's an old demo on Openprocessing. I might take a slightly different approach to setting the buffer colours these days though - e.g. using a single channel to store the index rather than relying on the fact that colours in Processing are stored as ints.

The benefit to this approach is that you can apply it to any arbitrary shape (including those with holes in). Just make sure you don't anti-alias anything in your buffer image and bear in mind the possible performance hit of updating the buffer if you're dealing with animated content.