问题
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.
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
回答1:
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;
}
};
回答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.
回答3:
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.
来源:https://stackoverflow.com/questions/7797353/jfreechartjava-how-to-draw-lines-that-is-partially-dashed-lines-and-partiall