使用JFreeChart作为X标签的日期

3
我正在实现一个应用程序,从COVID-19信息网检索CSV数据。
我已经制作了一个解析器,可以获取特定地点(加那利群岛)每天的病例数。
String url = "https://cnecovid.isciii.es/covid19/resources/datos_ccaas.csv";
String[] contents = HTTPFileDownloader.downloadFromURL(url).split("\n");

for(String i : contents) {
    if(isCanaryIslandData(i)) {
        String[] line = i.split(",");
        String[] date = line[1].split("-");    // "YYYY-MM-DD"

        int cases = Integer.parseInt(line[2]);

        casesPerDay.add(cases);
     }
 }

现在我想制作一个显示数据的图表。类似于这样:

Desired Output

目前我正在使用ArrayList存储值(仅用于测试)。我知道我需要存储日期和病例数,但我不知道应该使用哪种类型的数据集。

我想制作一条线和一条柱形图。我已经成功做到了:

enter image description here

但是正如我所说的,我希望找到一种方法来显示日期作为x标签,就像示例中显示的那样。
我尝试使用CategoryDataset,但它打印每个单独的x标签,因此根本无法阅读。我知道XYSeries可以完成这项技巧,就像之前展示的那样,但我不知道如何插入字符串作为标签,而不是整数。
希望我解释得清楚。
1个回答

2

我使用TimeSeriesCollection成功完成了它。

TimeSeries series = new TimeSeries("Cases per Day");
String url = "https://cnecovid.isciii.es/covid19/resources/datos_ccaas.csv";
String[] contents = HTTPFileDownloader.downloadFromURL(url).split("\n");

    for(String i : contents) {
        if(isCanaryIslandData(i)) {
            String[] line = i.split(",");
            String[] date = line[1].split("-");

            int year = Integer.parseInt(date[0]);
            int month = Integer.parseInt(date[1]);
            int day = Integer.parseInt(date[2]);

            int cases = Integer.parseInt(line[2]);

            series.add(new Day(day, month, year), cases);

        }
    }

然后是关于图表类的内容:
    TimeSeriesCollection dataset = new TimeSeriesCollection();

    dataset.addSeries(series);

    JFreeChart chart = ChartFactory.createXYLineChart(
               "Line Chart",
               "x",
               "y",
               dataset,
               PlotOrientation.VERTICAL,
               true,
               true,
               false);

   ChartPanel chartPanel = new ChartPanel(chart);
   chartPanel.setMouseWheelEnabled(true);
   chartPanel.setPreferredSize(new java.awt.Dimension(560,367));

   XYPlot plot = (XYPlot) chart.getPlot();
   DateAxis dateAxis = new DateAxis();
   dateAxis.setDateFormatOverride(new SimpleDateFormat("dd-MM-yyyy"));
   plot.setDomainAxis(dateAxis);

并输出:

在这里输入图像描述

我不知道它是否是最好的解决方案,但它能完成工作。


还要考虑java.time,可以在这里看到。 - trashgod

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接