jfreechart时序图x轴格式显示
转发请注明转发来源,尊重原创
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.StandardChartTheme;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.text.SimpleDateFormat;
/**
* @author Laker24
* @date 2019/12/18 11:03
*/
public class javachart {
public static void main(String[] args){
JFrame jf = new JFrame();
//设置统计图大小
jf.setSize(800, 600);
jf.setLocationRelativeTo(null);
//读txt文件并显示
jf.add(new ChartPanel(tongjitu("时序图绘制","F:/XX/XXXXX.txt")));
jf.setVisible(true);
}
//读取txt文件中的数据
public static int[] readTxt(String filePath){
FileInputStream fin = null;
try {
fin = new FileInputStream(filePath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
InputStreamReader reader = new InputStreamReader(fin);
BufferedReader buffReader = new BufferedReader(reader);
String strTmp = "";
int[] result = null;
while(true){
try {
if (!((strTmp = buffReader.readLine())!=null)) break;
} catch (IOException e) {
e.printStackTrace();
}
String resultString[] =strTmp.replace(","," ").split(" ");
result = new int[resultString.length];
for (int i = 0; i < resultString.length ; i++) {
result[i]=Integer.parseInt(resultString[i]);
System.out.println(result[i]);
}
}
try {
buffReader.close();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
//统计数据定义
public static XYDataset shuju(String filepath){
XYSeries xyseries = new XYSeries("新数据");
//将读取的txt的数组存入xyseries
int[] result = readTxt(filepath);
int index=0;
while(index<result.length) {
xyseries.add(index, result[index+1]);
index+=2;
}
XYSeriesCollection xyseriescollection = new XYSeriesCollection();
xyseriescollection.addSeries(xyseries);
return xyseriescollection;
}
//生成时序图
public static JFreeChart tongjitu(String chartName,String filepath) {
//防止乱码和设置字体
StandardChartTheme standardChartTheme = new StandardChartTheme("CN");
standardChartTheme.setExtraLargeFont(new Font("宋体", Font.BOLD, 25));
standardChartTheme.setRegularFont(new Font("宋书", Font.PLAIN, 15));
standardChartTheme.setLargeFont(new Font("宋书", Font.PLAIN, 15));
ChartFactory.setChartTheme(standardChartTheme);
// 创建时序图
JFreeChart chart = ChartFactory.createTimeSeriesChart(chartName, "time", "value", shuju(filepath), false, false, false);
XYPlot plot = (XYPlot) chart.getXYPlot();
// 显示网格线
plot.setDomainGridlinesVisible(true);
// 获取x轴,即时间轴
DateAxis dateaxis =(DateAxis)plot.getDomainAxis();
//这里原本是秒+毫秒的组合,由于横轴的数据是以毫秒为单位,就直接显示一个五位数,比如数字400,这里显示00400,但这种方式只能显示0-99999
SimpleDateFormat format = new SimpleDateFormat("ssSSS");
dateaxis.setDateFormatOverride(format);
plot.getRangeAxis().setUpperMargin(1);// 设置顶部Y坐标轴间距,防止数据无法显示
plot.getRangeAxis().setLowerMargin(1);// 设置底部Y坐标轴间距
return chart;
}
}