在文件inputxlsx中有一个P1工作表用其中A2-A50的数据作为水平轴水平轴要为时间格式用B2-B50的数据作为垂直轴用C2-C50的数据作为次要垂直轴用JFreeCharts库实现
首先,您需要在代码中导入JFreeCharts库。可以使用以下代码行导入库:
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.CombinedDomainXYPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.XYDataset;
然后,您可以使用以下代码读取Excel文件中的数据:
import org.apache.poi.ss.usermodel.*;
// 读取Excel文件
Workbook workbook = WorkbookFactory.create(new File("input.xlsx"));
// 获取P1工作表
Sheet sheet = workbook.getSheet("P1");
// 创建时间序列数据集
TimeSeriesCollection dataset = new TimeSeriesCollection();
// 读取A2-A50的数据作为时间序列的水平轴
Row xRow = sheet.getRow(1);
for (int i = 1; i <= 49; i++) {
Cell cell = xRow.getCell(i);
Date date = cell.getDateCellValue();
TimeSeries series = new TimeSeries("Series " + i);
series.add(new Day(date), 0);
dataset.addSeries(series);
}
// 创建垂直轴数据集
DefaultCategoryDataset verticalDataset = new DefaultCategoryDataset();
// 读取B2-B50的数据作为垂直轴
Row yRow = sheet.getRow(1);
for (int i = 1; i <= 49; i++) {
Cell cell = yRow.getCell(i);
double value = cell.getNumericCellValue();
verticalDataset.addValue(value, "Vertical Axis", "Series " + i);
}
// 创建次要垂直轴数据集
DefaultCategoryDataset secondaryVerticalDataset = new DefaultCategoryDataset();
// 读取C2-C50的数据作为次要垂直轴
Row y2Row = sheet.getRow(2);
for (int i = 1; i <= 49; i++) {
Cell cell = y2Row.getCell(i);
double value = cell.getNumericCellValue();
secondaryVerticalDataset.addValue(value, "Secondary Vertical Axis", "Series " + i);
}
接下来,您可以使用以下代码创建图表并显示出来:
// 创建水平轴对象
DateAxis xAxis = new DateAxis("Time");
// 创建垂直轴对象
NumberAxis yAxis = new NumberAxis("Vertical Axis");
// 创建次要垂直轴对象
NumberAxis secondaryYAxis = new NumberAxis("Secondary Vertical Axis");
// 创建水平轴绘图区域对象
XYPlot plot = new XYPlot(dataset, xAxis, yAxis, null);
// 创建次要垂直轴绘图区域对象
XYPlot secondaryPlot = new XYPlot(secondaryVerticalDataset, xAxis, secondaryYAxis, null);
// 创建组合绘图区域对象
CombinedDomainXYPlot combinedPlot = new CombinedDomainXYPlot(xAxis);
// 将水平轴绘图区域对象和次要垂直轴绘图区域对象添加到组合绘图区域对象中
combinedPlot.add(plot);
combinedPlot.add(secondaryPlot);
// 创建图表对象
JFreeChart chart = new JFreeChart("Chart Title", JFreeChart.DEFAULT_TITLE_FONT, combinedPlot, true);
// 创建图表框架对象
ChartFrame frame = new ChartFrame("Chart", chart);
// 设置图表框架的大小
frame.setSize(800, 600);
// 显示图表框架
frame.setVisible(true);
这样,您就可以使用JFreeCharts库创建一个图表,其中水平轴为时间格式,垂直轴为B2-B50的数据,次要垂直轴为C2-C50的数据。
原文地址: https://www.cveoy.top/t/topic/iikZ 著作权归作者所有。请勿转载和采集!