We are trying to display Timeseries chart with dynamic x-axis values. We are using the below code, which contains date values in the first argument.
Can any one suggest the way how to set minimum date to x-axis tick values
for(int i=NUMBER_TWELEVE;i>=NUMBER_ZERO;i--)
{
series1.add(new Week(new Date(p1.get(i).getYear(),p1.get(i).getMonth(),p1.get(i).getDate())),actualValues.get(i));
}
TimeSeries series2 = new TimeSeries(key+" Expectation");
for(int i=NUMBER_TWELEVE;i>=NUMBER_ZERO;i--)
{
series2.add(new Week(new Date(p1.get(i).getYear(),p1.get(i).getMonth(),p1.get(i).getDate())),expectedValues.get(i));
}
TimeSeriesCollection xyDataset = new TimeSeriesCollection();
xyDataset.addSeries(series1);
xyDataset.addSeries(series2);
We are seeting minimum date using below.
Date minDate = new Date(p1.get(NUMBER_TWELEVE).getYear(),p1.get(NUMBER_TWELEVE).getMonth(),p1.get(NUMBER_TWELEVE).getDate());
DateAxis dateaxis = (DateAxis) plot.getDomainAxis();
dateaxis.setAutoRange(false);
dateaxis.setAutoTickUnitSelection(false);
dateaxis.setMinimumDate(minDate);
Related
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.
im using jfree chart in my application. For my application i need to mark only first and last value of the x axis and also tick mark.
I've tried
String Male1 = "First";
String Male2 = "sec";
String Female1 = "0-4";
String Female2 = "5-18";
String Female3 = "19-45";
String Female4 = "46-64";
String Female5 = "65+";
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
dataset.addValue(202, Male1, Female1);
dataset.addValue(130, Male2, Female1);
dataset.addValue(216, Male1, Female2);
dataset.addValue(0, Male2, Female2);
dataset.addValue(248, Male1, Female3);
dataset.addValue(458, Male2, Female3);
dataset.addValue(517, Male1, Female4);
dataset.addValue(623, Male2, Female4);
dataset.addValue(1481, Male1, Female5);
dataset.addValue(680, Male2, Female5);
final JFreeChart chart = ChartFactory.createBarChart(
"", "", "", dataset,
PlotOrientation.HORIZONTAL, true, true, false);
CategoryPlot plot = chart.getCategoryPlot();
plot.setBackgroundPaint(Color.WHITE);
plot.setOutlineVisible(false);
plot.setRangeGridlinesVisible(false);
plot.setRangeGridlineStroke(new BasicStroke(0.2f));
plot.setAxisOffset(RectangleInsets.ZERO_INSETS);
NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setAxisLinePaint(Color.decode("#C1C1C1"));
rangeAxis.setAxisLineVisible(true);
rangeAxis.setTickMarksVisible(false);
rangeAxis.setTickMarkOutsideLength(0f);
final CategoryAxis categoryAxis = (CategoryAxis) plot.getDomainAxis();
categoryAxis.setTickMarksVisible(false);
categoryAxis.setAxisLineVisible(false);
BarRenderer br = new BarRenderer();
br.setItemMargin(0.03);
br.setShadowVisible(false);
br.setBarPainter(new StandardBarPainter());
br.setSeriesPaint(0, Color.decode("#999999"));
br.setSeriesPaint(1, Color.decode("#CCCCCC"));
chart.getCategoryPlot().setRenderer(br);
chart.removeLegend();
try {
ChartUtilities.saveChartAsPNG(new File("/media/hari/668ea9a3-d26c-4896-a2f0-756dfb532756/jfreeBarchart.png"), chart, 280, 180);
System.out.println("=====Bar chart=====");
} catch (Exception e) {
e.printStackTrace();
}
For the above code im getting
But my expectation is
Please help me to get the expected chart in jfree bar chart
If I understood correctly you want to only display two ticks (0 and 1500) and add a noticeable inside tick mark to both.
To display only two ticks you can call setTickUnit with the appropriate size argument. This size will be used by the axis object to generate the visible ticks.
To add tick marks on the inside you can call setTickMarkInsideLength.
So adding these three lines should do the trick:
rangeAxis.setTickUnit(new NumberTickUnit(1500));
rangeAxis.setTickMarksVisible(true);
rangeAxis.setTickMarkInsideLength(3f);
i have managed to plot an xy chart with a few points using jfreechart.
what am trying to do is to be able to click anywhere on the line that has been drawn and get its x or y axis value.
Can anybody help me out ?
its my first time using j freechart and i feel somewhat lost.
i created the dataset and generated the chart so far.
TimeSeries s = new TimeSeries("security", Day.class);
while (rate_i.hasNext()) {
rate r = (rate) rate_i.next();
Calendar cal = Calendar.getInstance();
cal.setTime(r.d);
int month = cal.get(Calendar.MONTH) + 1;
int day = cal.get(Calendar.DATE);
int year = cal.get(Calendar.YEAR);
s.add(new Day(day, month, year), r.rate);
}
TimeSeriesCollection ds = new TimeSeriesCollection();
ds.addSeries(s);
JFreeChart chart = ChartFactory.createTimeSeriesChart(
"Security Performance over time.", // title
"Date", // x-axis label
"Value", // y-axis label
ds, // data
true, // create legend?
true, // generate tooltips?
false // generate URLs?
);
XYPlot xyplot = (XYPlot) chart.getPlot();
xyplot.setDomainPannable(true);
xyplot.setRangePannable(false);
xyplot.setDomainCrosshairVisible(true);
xyplot.setRangeCrosshairVisible(true);
org.jfree.chart.renderer.xy.XYItemRenderer xyitemrenderer = xyplot
.getRenderer();
if (xyitemrenderer instanceof XYLineAndShapeRenderer) {
XYLineAndShapeRenderer xylineandshaperenderer =
(XYLineAndShapeRenderer) xyitemrenderer;
xylineandshaperenderer.setBaseShapesVisible(false);
}
DateAxis dateaxis = (DateAxis) xyplot.getDomainAxis();
dateaxis.setDateFormatOverride(
new SimpleDateFormat("EEE, MMM d, ''yy"));
ChartFrame frame = new ChartFrame("Chart", chart);
frame.setVisible(true);
frame.setSize(700, 900);
Add a ChartMouseListener to your enclosing ChartPanel; examples are seen here and here. The ChartEntity will contain details about the mouse target.
My problem is that I don't know how to assign time in such format 00:00:00.000 to X axis in JFreeChart.
I'm writing an application which will get the data from CSV file where the columns look like this:
time accelerationX accelerationY accelerationZ
I looked for example but I didn't find anything which might help me.
My code:
public ChartService() {
final CombinedDomainXYPlot plot = new CombinedDomainXYPlot(new DateAxis("Time"));
this.datasets = new TimeSeriesCollection[SUBPLOT_COUNT];
for (int i = 0; i < SUBPLOT_COUNT; i++) {
this.lastValue[i] = 100.0;
final TimeSeries series = new TimeSeries(Y_AXIS_TITLES[i], Millisecond.class);
// this.series.add(new SimpleDateFormat("hh:mm:ss.mmm"), 0.2222);
this.datasets[i] = new TimeSeriesCollection(series);
final NumberAxis rangeAxis = new NumberAxis(Y_AXIS_TITLES[i]);
rangeAxis.setAutoRangeIncludesZero(false);
final XYPlot subplot = new XYPlot(
this.datasets[i], null, rangeAxis, new StandardXYItemRenderer()
);
subplot.setBackgroundPaint(Color.lightGray);
subplot.setDomainGridlinePaint(Color.white);
subplot.setRangeGridlinePaint(Color.white);
plot.add(subplot);
}
final JFreeChart chart = new JFreeChart("Dynamic Data Demo 3", plot);
chart.setBorderPaint(Color.black);
chart.setBorderVisible(true);
chart.setBackgroundPaint(Color.white);
plot.setBackgroundPaint(Color.lightGray);
plot.setDomainGridlinePaint(Color.white);
plot.setRangeGridlinePaint(Color.white);
final ValueAxis axis = plot.getDomainAxis();
axis.setAutoRange(true);
axis.setFixedAutoRange(60000.0); // 60 seconds
final JPanel content = new JPanel(new BorderLayout());
final ChartPanel chartPanel = new ChartPanel(chart);
content.add(chartPanel);
chartPanel.setPreferredSize(new java.awt.Dimension(790, 620));
chartPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
this.add(content);
}
Please help !!!
String s = "10:00:00.000";
SimpleDateFormat f = new SimpleDateFormat("HH:MM:SS.SSS");
Date parsedDate = f.parse(s);
You can convert the given time to date as above and then you can use the Date object to create http://www.jfree.org/jfreechart/api/gjdoc/org/jfree/data/time/Millisecond.html#Millisecond:Date
I am using Jfree chart 0.9.20's XYLineChartDemo for plotting the execution time of running processes in a program. My X axis denotes the time and Y axis should denote the Pid. How can I edit the Jfreechart files to make my Y axis to denote values I want and not numbers 0-range?? Also is there a way to make the line plotted to be made thicker in width?
study this:
public JFreeChart createChart(String axisX, String axisY){
JFreeChart chart = ChartFactory.createTimeSeriesChart(null, axisX, axisY, dataSeries, true, true, false);
final XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
renderer.setSeriesLinesVisible(0,true);
renderer.setSeriesShapesVisible(0, true);
//percentage (y-axis)
final NumberAxis percentAxis = new NumberAxis(axisY);
percentAxis.setInverted(false);
percentAxis.setRange(0.0, 100.0);
//time (x-axis)
final DateAxis timeAxis = new DateAxis(axisX);
timeAxis.setStandardTickUnits(DateAxis.createStandardDateTickUnits(TimeZone.getDefault(), Locale.ENGLISH));
double range = 0;
switch (format){
case ONE_MINUTE_RANGE: range = 60*1000; break;
case TEN_MINUTE_RANGE: range = 10*60*1000; break;
case ONE_HOUR_RANGE: range = 60*60*1000; break;
}
timeAxis.setRange(System.currentTimeMillis()-range/2, System.currentTimeMillis()+range/2); //time duration based on format chosen
XYPlot plot = chart.getXYPlot();
plot.setDomainAxis(timeAxis);
plot.setRangeAxis(percentAxis);
plot.setBackgroundPaint(Color.white);
plot.setRangeGridlinePaint(Color.gray);
plot.setRangeZeroBaselinePaint(Color.gray);
plot.setDomainGridlinePaint(Color.gray);
plot.setForegroundAlpha(0.5f);
plot.setRenderer(renderer);
chart.setBackgroundPaint(Color.white);
return chart;
}