JFreeChart - 具有垂直DateAxis的BarChart

时间:2014-10-29 13:30:44

标签: java datetime jfreechart bar-chart

我需要制作在垂直轴上有日期的条形图。它将显示该软件最后一次使用的时间戳。

它看起来像标准条形图,但在纵轴上我需要日期而不是数字。

感谢您的帮助

编辑: 这是创建图表的工作示例,看起来几乎像我想要的那样。

private void createSoftwareLastUsageChart() throws ParseException {
    Date from = new Date(new Date().getTime() - (15 * 24 * 60 * 60 * 1000L));
    List<SwLastUsed> databaseStatisticsItems = getTestData();

    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    for (SwLastUsed soft : databaseStatisticsItems) {
        dataset.addValue(soft.lastUsed.getTime() - from.getTime(), "Software", soft.name);
    }

    JFreeChart chart = ChartFactory.createBarChart("Software last usage", "Values", "Time", dataset, PlotOrientation.VERTICAL, false, false, false);
    CategoryPlot plot = (CategoryPlot) chart.getPlot();

    CategoryAxis domainAxis = (CategoryAxis) plot.getDomainAxis();
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);
    JFrame window = new JFrame();

    JPanel pnl = new JPanel();
    ChartPanel chPnl = new ChartPanel(chart);
    chPnl.setPreferredSize(new Dimension(800, 600));
    pnl.add(chPnl);
    window.setContentPane(pnl);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.pack();
    window.setVisible(true);
}

private List<SwLastUsed> getTestData() throws ParseException {
    List<SwLastUsed> sw = new ArrayList<>();
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    sw.add(new SwLastUsed("CHROME", format.parse("2014-11-03 11:24:20.456+01")));
    sw.add(new SwLastUsed("INTERNET_EXPLORER 10.* x64", format.parse("2014-11-03 11:15:28.124+01")));
    sw.add(new SwLastUsed("INTERNET_EXPLORER 11.*", format.parse("2014-11-03 11:15:28.124+01")));
    sw.add(new SwLastUsed("INTERNET_EXPLORER 10.* x86", format.parse("2014-11-03 11:08:35.359+01")));
    sw.add(new SwLastUsed("FIREFOX x86", format.parse("2014-10-21 09:38:17.109+02")));
    sw.add(new SwLastUsed("SAFARI", format.parse("2014-10-20 15:00:26.526+02")));
    sw.add(new SwLastUsed("FIREFOX x64", format.parse("2014-10-20 14:55:47.886+02")));
    return sw;
}

private class SwLastUsed {
    public String name;
    public Date lastUsed;

    public SwLastUsed(String name, Date lastUsed) {
        this.name = name;
        this.lastUsed = lastUsed;
    }
}

我想要做的一件事是将左侧垂直轴上的时间值(以毫秒为单位)更改为日期 - 时间格式。

2 个答案:

答案 0 :(得分:2)

使用ChartFactory.createXYBarChart()并为true参数指定dateAxis,为PlotOrientation.HORIZONTAL参数指定orientation

答案 1 :(得分:0)

DateAxis xAxis = new DateAxis("Date"); xAxis.setVerticalTickLabels(true); plot.setDomainAxis(xAxis);