JFreechart(Java) - How to draw lines that is partially dashed lines and partially solid lines?
Asked Answered
M

3

5

I'm going to plot a line chart that will change from solid line to dashed line to to indicate real data and forecasting data. I'm not sure if i need to extend some of the classes like XYLineAndShapeRenderer or something else, or maybe there is some convenient way to achieve this?

Here is a demostration graph i plotted using Excel.

enter image description here

I am talking about the gray lines in the graph. That is what i want. I don't know if there is a renderer that allow me to indicate which range dashed or solid

Mattress answered 17/10, 2011 at 17:32 Comment(0)
S
13

There are two ways I can think of for doing this. Neither of them are elegant, but that may be the reality of your problem.

One is that you could define two series that happen to connect to each other. This is probably your best option, but you will also have to fix your legend.

This would make your second series show as a dashed line:

plot.getRenderer().setSeriesStroke(
    1, 
    new BasicStroke(
        2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND,
        1.0f, new float[] {6.0f, 6.0f}, 0.0f
    )

Edit: My original "second option" was wrong. Here is a better way to do it:

Override the getItemStroke() method in AbstractRenderer.

     final BasicStroke dashedStroke = new BasicStroke(
                  2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND,
                  1.0f, new float[] {6.0f, 6.0f}, 0.0f);
     XYLineAndShapeRenderer render = new XYLineAndShapeRenderer() {
        @Override
        public Stroke getItemStroke(int row, int column) {
            if (column < dashedThreshold) {
                return lookupSeriesStroke(row);
            } else {
               return dashedStroke;
            }
       };
Spend answered 17/10, 2011 at 18:2 Comment(2)
+1 ... though getItemStroke shouldn't create a new BasicStroke every time. It's going to get called for every item for every series every time its repainted.Jillane
Thank you. I am thinking the same way too. Just wanna see if there is a simpler solution, thanks anyway :)Mattress
J
2

You can extend XYLineAndShapeRenderer, and override getItemStroke where you provide a different stroke for different items.

The default implementation simply returns the series stroke.

Jillane answered 17/10, 2011 at 18:11 Comment(1)
+1 Just saw your solution after editing mine... I promise I wasn't trying to rip you off :PSpend
L
0

Maybe you should just define different data sets for the real vs forecast data. It would not only be simpler to change the line style, but the code would probably be clearer too.

Lapointe answered 17/10, 2011 at 17:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.