之前遇到过一个问题,需要用jfreechart来描点画图,获取shp文件的图形,后来用折线图实现,发现有个很大的问题,比如你的X坐标集合是{5,2,78,2,1},Y坐标集合是{54,23,78,21,3};正常情况下我们想要的肯定是(5,54)—>(2,23)—>(78,78)—>(2,21)—>(1,3)按照这个顺序连接,但实际上jfreechart他是先会给xy集合各自排序,然后重新连接,就会变成(1,3)—>(2,21)—>(2,23)—>(5,54)—>(78,78)
后来网上找了很多,都没有想要的方法,唯一可行的貌似应该是用散点图来连接,但散点图我只能创建点,还不懂连接,所以没办法用了强硬的老办法,使用折线图,每一条线都是一个对象来创建,代码如下:
public static void main(String args[]) {
StandardChartTheme mChartTheme = new StandardChartTheme("CN");
mChartTheme.setLargeFont(new Font("黑体", Font.BOLD, 20));
mChartTheme.setExtraLargeFont(new Font("宋体", Font.PLAIN, 15));
mChartTheme.setRegularFont(new Font("宋体", Font.PLAIN, 15));
ChartFactory.setChartTheme(mChartTheme);
XYSeriesCollection mCollection = GetCollection();
JFreeChart mChart = ChartFactory.createXYLineChart(
"测试图",
"x轴",
"y轴",
mCollection, //数据集
PlotOrientation.VERTICAL, //绘制方向
true, //显示图例
true, //标准生成器
false); //是否生成超链接
XYPlot xyplot = mChart.getXYPlot();
NumberAxis yAxis = (NumberAxis) xyplot.getRangeAxis(); //获取Y轴
yAxis.setAutoRangeIncludesZero(false); //不强制显示0,让图形显示在图中,自适应
xyplot.setBackgroundPaint(Color.WHITE); //折线背景
xyplot.setRangeGridlinePaint(Color.gray); //虚线颜色
/*设置折线粗细,颜色*/
XYLineAndShapeRenderer xylineandshaperenderer = (XYLineAndShapeRenderer) xyplot.getRenderer();
xylineandshaperenderer.setSeriesStroke(0, new BasicStroke(2F)); //0表示第一个折线
xylineandshaperenderer.setSeriesPaint(0,Color.BLACK);
/*
xylineandshaperenderer.setSeriesStroke(1, new BasicStroke(2F));
xylineandshaperenderer.setSeriesStroke(2, new BasicStroke(2F));
xylineandshaperenderer.setSeriesStroke(3, new BasicStroke(2F));
*/
ChartFrame mChartFrame = new ChartFrame("测试图", mChart);
mChartFrame.pack();
mChartFrame.setVisible(true);
mChart.getLegend().setVisible(false); //设置标签隐藏
}
public static XYSeriesCollection GetCollection(){
int X[]={5,2,78,2,1};
int Y[]={54,23,78,21,3};
XYSeriesCollection mCollection = new XYSeriesCollection();
XYSeries m[] = new XYSeries[4]; //五个点需要四条折线
for(int i=0;i<4;i++) {
m[i]=new XYSeries(i);
m[i].add(X[i],Y[i]);
m[i].add(X[i+1],Y[i+1]);
mCollection.addSeries(m[i]);
}
// mCollection.addSeries(mSeriesForth);
return mCollection;
}
额外补充一个让图标居中自适应显示的代码:
//JFreeChart mChart = ChartFactory.createXYLineChart()
XYPlot xyplot = mChart.getXYPlot();
NumberAxis yAxis = (NumberAxis) xyplot.getRangeAxis();
yAxis.setAutoRangeIncludesZero(false);
再补充一个让图标的标签隐藏掉的代码
//JFreeChart mChart = ChartFactory.createXYLineChart()
mChart.getLegend().setVisible(false);