我想在Java应用程序中使用JFreeChart
添加多个系列来创建折线图。我从数据库中检索值并使用这些值生成图表。但是当时图表上只出现一条线。任何人都可以帮助同时显示行。
try{
String query = "SELECT hardware, SUM(Quantity) FROM request_1v2 where date "
+ "between '"+txt1+"' and '"+txt2+"'group by hardware";
String querys = "SELECT hardware, SUM(Quantity) FROM request_1v2 where date "
+ "between '"+txt5+"' and '"+txt6+"'group by hardware";
JDBCCategoryDataset dataset1 = new JDBCCategoryDataset(dbConnection.dbConnector());
dataset1.executeQuery(query);
JDBCCategoryDataset dataset2 = new JDBCCategoryDataset(dbConnection.dbConnector());
dataset2.executeQuery(querys);
System.out.println(dataset1);
JFreeChart chart = ChartFactory.createLineChart("Hardware booked out between "+txt1+" and "+txt2+"", "Hardware", "Number", dataset1, PlotOrientation.VERTICAL, false, true, true);
ChartPanel chartPanel = new ChartPanel(chart);
panel.removeAll();
panel.add(chartPanel, BorderLayout.CENTER);
panel.validate();
JFreeChart chart1 = ChartFactory.createLineChart("Hardware booked out between "+txt5+" and "+txt6+"", "Hardware", "Number", dataset2, PlotOrientation.VERTICAL, false, true, true);
ChartPanel chartPanel1 = new ChartPanel(chart1);
panel_1.removeAll();
panel_1.add(chartPanel1, BorderLayout.CENTER);
panel_1.validate();
String sql = "select * from request_1v2 where Date between '"+txt1+"' and '"+txt2+"' order by date desc";
PreparedStatement pst = connection.prepareStatement(sql);
pst=connection.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
}catch (Exception e){
JOptionPane.showConfirmDialog(null, e);
}
答案 0 :(得分:2)
JDBCCategoryDataset
指定"第一列是类别名称和剩余列值(每列代表一个系列)。"要获取两个系列,您需要选择三个属性。应该可以在单个查询中使用aliases来区分对同一个表的引用,如建议的here,可能是这样的:
SELECT hardware, SUM(t1.quantity) AS Series1, SUM(t2.quantity) AS Series2
FROM request_1v2 t1, request_1v2 t2
WHERE t1.date BETWEEN …
或者,您可以将两个数据集合并为新的CategoryDataset
,并使用它来创建单个图表。
DefaultCategoryDataset dcd = new DefaultCategoryDataset();
for (int i = 0; i < dataset1.getColumnCount(); i++) {
dcd.addValue(dataset1.getValue(dataset1.getRowKey(0), dataset1.getColumnKey(i)),
dataset1.getRowKey(0), dataset1.getColumnKey(i));
dcd.addValue(dataset2.getValue(dataset2.getRowKey(0), dataset2.getColumnKey(i)),
dataset2.getRowKey(0), dataset1.getColumnKey(i));
}
JFreeChart chart = ChartFactory.createLineChart(…, dcd, …);