I am implementing an application which retrieves CSV data from COVID-19 info web.
I have made a parser which gets the cases per day of an specific place (Canary Island).
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);
}
}
Now I want to make a chart displaying the data. Something like this:
Currently I am storing the values in an ArrayList (just for testing). I know I will need to store the date and the number of cases, but I don't know which type of dataset should I use.
I want to make a line and a bar chart. I have managed to do it:
But as I have said, I want to find a way to display the dates as the x labels as shown in the example.
I tried with a CategoryDataset, but that prints every single x label so it won't be readable at all. I know XYSeries can do the trick as shown before, but I don't know how to insert a string as label instead of an integer.
Hope I explained it well.
I managed to do it using 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);
}
}
Then on the chart class:
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);
And output:
I don't know if it's the best solution, but it does the work.