james james - 7 months ago 27
Java Question

How to get the bars in a bar chart start from the x-axis in java?

As you can see in the picture, the bars in the chart starts below the x-axis. How do I fix it so that it starts from the x-axis line? Please suggest me a fix and also I would be helpful to know where I am going wrong.

g2.setColor(Color.red);
for (int j = 0; j < DataArray.length; j++) {

int x1 = x0 + (int) (j * xScale) + PAD;
double y1 = (int) ((MaxValue - DataArray[j]) * yScale + PAD) - 2;
g2.fillRect(x1 + 2, (int) y1 + 1 , w - (PAD * 42), h);

}

}
} catch (Exception e) {

}
}
repaint();

}


g2.setColor(Color.red);
for (int j = 0; j < DataArray.length; j++) {

int x1 = x0 + (int) (j * xScale) + PAD;
double y1 = (int) ((MaxValue - DataArray[j]) * yScale + PAD) - 2;
g2.fillRect(x1 + 2, (int) y1 + 1 , w - (PAD * 42), h);

}

}
} catch (Exception e) {

}
}
repaint();

}

g2.setColor(Color.red);
for (int j = 0; j < DataArray.length; j++) {

int x1 = x0 + (int) (j * xScale) + PAD;
double y1 = (int) ((MaxValue - DataArray[j]) * yScale + PAD) - 2;
g2.fillRect(x1 + 2, (int) y1 + 1 , w - (PAD * 42), h);

}

}
} catch (Exception e) {

}
}
repaint();

}

g2.setColor(Color.red);
for (int j = 0; j < DataArray.length; j++) {

int x1 = x0 + (int) (j * xScale) + PAD;
double y1 = (int) ((MaxValue - DataArray[j]) * yScale + PAD) - 2;
g2.fillRect(x1 + 2, (int) y1 + 1 , w - (PAD * 42), h);

}

}
} catch (Exception e) {

}
}
repaint();

}

g2.setColor(Color.red);
for (int j = 0; j < DataArray.length; j++) {

int x1 = x0 + (int) (j * xScale) + PAD;
double y1 = (int) ((MaxValue - DataArray[j]) * yScale + PAD) - 2;
g2.fillRect(x1 + 2, (int) y1 + 1 , w - (PAD * 42), h);

}

}
} catch (Exception e) {

}
}
repaint();

}

Answer

A bar's fillRect() parameters should be left, top, width and height. Focusing on just the vertical size and position, as shown here, you can scale the bar height to the plot area height using a proportion:

barHeightInPixels : plotHeightInPixels :: value : maxDataValue

Solving for barHeightInPixels,

panelHeightInPixels := panel.getHeight();
plotHeightInPixels := panelHeightInPixels - axisOffset;
barHeightInPixels := value * plotHeightInPixels / maxDataValue;

Now use the scaled height:

g2.fillRect(
    barCenter - (barWidth / 2),
    panelHeightInPixels - barHeightInPixels - axisOffset,
    barWidth,
    barHeightInPixels);

image

To see how additional features are implemented, study the code provided by a chart library, as suggested in this answer to your previous question on this topic.