Jfree chart change Y axis data - java

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;
}

Related

Issues creating a jfreechart score bar/chart

I am trying to create a score/percent/status bar using jfreechart.
The image show what it's suppose to look like.Good ScoreChart
It looks like one bar from a stack chart, so I try to adjust from there. (Do let me know if there is a better way to do this other than the stack chart)
I am seeing multiple issues doing the bar this way. I can't make the start line and end line longer. I can't put text on top of both start/end line.(I think they get chopped off) I cannot put center text in the middle of the bar either...
Here is what I got now. Bad ScoreChart
Here is the code for the bad Chart.
public JFreeChart createChart(final CategoryDataset dataset) {
final JFreeChart chart = ChartFactory.createStackedBarChart(null, null, null, dataset,
PlotOrientation.HORIZONTAL, false, false, false);
chart.setBackgroundPaint(Color.WHITE);
CategoryPlot plot = chart.getCategoryPlot();
((BarRenderer) plot.getRenderer()).setBarPainter(new StandardBarPainter());
plot.getRenderer().setSeriesPaint(0, DONUT_CHART_ORANGE);
plot.getRenderer().setSeriesPaint(1, DONUT_CHART_BLUE);
ValueAxis rangeAxis = plot.getRangeAxis();
rangeAxis.setVisible(false);
CategoryAxis domainAxis = plot.getDomainAxis();
domainAxis.setVisible(false);
plot.setRangeGridlinesVisible(false);
plot.setBackgroundPaint(Color.WHITE);
plot.setOutlineVisible(false);
CategoryItemRenderer renderer = ((CategoryPlot) chart.getPlot()).getRenderer();
//renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
renderer.setBaseItemLabelGenerator(new CustomItemLabelGenerator());
renderer.setBaseItemLabelsVisible(true);
ItemLabelPosition position = new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER);
renderer.setBasePositiveItemLabelPosition(position);
Marker startMarker = new ValueMarker(0);
startMarker.setPaint(Color.black);
startMarker.setLabel("000000000");
startMarker.setStroke(new BasicStroke(1.0f));
startMarker.setLabelOffset( new RectangleInsets(UnitType.ABSOLUTE, 10,0,0,0));
startMarker.setLabelAnchor(RectangleAnchor.TOP_RIGHT) ;
startMarker.setLabelTextAnchor(TextAnchor.BASELINE_CENTER);
plot.addRangeMarker(startMarker);
Marker endMarker = new ValueMarker(1000);
endMarker.setPaint(Color.black);
endMarker.setLabel("1000");
endMarker.setStroke(new BasicStroke(1.0f));
endMarker.setLabelAnchor(RectangleAnchor.TOP);
endMarker.setLabelTextAnchor(TextAnchor.TOP_RIGHT);
plot.addRangeMarker(endMarker);
RectangleInsets chartRectangle = new RectangleInsets(35, 0, 35, 0);
chart.setPadding(chartRectangle);
return chart;
}
public CategoryDataset createDataset() {
double inValue = 775;
double[][] data = new double[][] {
{ inValue },
{ 1000- inValue },
};
return DatasetUtilities.createCategoryDataset("A", "B", data);
}
Any Idea how to move the text so they show up on top of the lines and at the center of the bar?
Can we adjust the line width at the beginning and the end?
Thanks for any idea/info.

How to clean up plotted chart and restart the graph plotting from left end

I am trying to plot a real time graph using the data from serial port which arrives approx 1 sample/5 msec. So it is basically a Integer_Value Vs Time graph. Below is code to draw graph using JFreeChar (ScatterChart). In receive event handler of serial port listener I call method xySeries.add(x, y); with appropriate x and y co-ordinates.
Now plot appearance as expected is like
1. start from left end point of chart
2. Plot till right end
3. Restart from left end point of char
4. keep repeating this refresh cycles as I keep receiving continuous data over serial port.
However, I am stuck with problem #3 and #4. How to clean off the chart and restart from left end point? Also in #1 and #2 I am able to plot the points but it starts somewhere in right bottom end of chart. But I have used
xyPlot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_LEFT);
xyPlot.setDomainAxisLocation(AxisLocation.BOTTOM_OR_LEFT);
which should ideally start from bottom left end of chart, but it does not.
Would appreciate some pointers in this direction
Thank you in advance.
public void addPoint(Number x, Number y) {
Comment:This function is called from Serial Port receive event handler that supplies X,Y values
XYItemRenderer renderer = xyPlot.getRenderer();
//System.out.println("addPoint y = " + y.doubleValue() + " minThresholdMarker" + minThresholdMarker);
if(y.doubleValue() > minThresholdMarker) {
GradientPaint gPaint = new GradientPaint(2.0f, 6.0f, Color.lightGray, 2.0f, 6.0f, Color.green);
xyPlot.setBackgroundPaint(gPaint);
renderer.setSeriesPaint(0, Color.green);
if(!countDownTimerRunning /*&& !bTimeOver */) {
timerCountDown = new Timer(1000, countDownTimeListener);
timerCountDown.setInitialDelay(0);
countDown = TREATMENT_DURATION;
countElapsed = 0;
timerCountDown.start();
countDownTimerRunning = true;
timerDispPanel.setBackground(new Color(240, 230, 140));
}
}
else {
GradientPaint gPaint = new GradientPaint(4.0f, 6.0f, Color.lightGray, 3.0f, 6.0f, Color.lightGray);
xyPlot.setBackgroundPaint(gPaint);
if(countDownTimerRunning) {
stopCountDownTimer();
}
if(patientReady) {
renderer.setSeriesPaint(0, Color.blue);
}
else {
renderer.setSeriesPaint(0, Color.black);
}
timerDispPanel.setBackground(new Color(240, 240, 240));
if(bTimeOver)
bTimeOver = false;
else
bTimeOver = true;
}
xyPlot.setRenderer(renderer);
xySeries.add(x, y);
}
private ChartPanel drawChart() {
XYSeriesCollection xySeriesCollection = new XYSeriesCollection();
xySeries = new XYSeries("");
xySeriesCollection.addSeries(xySeries);
JFreeChart chart = ChartFactory.createScatterPlot("Breathing Co-ordinator", "Time (ms)", "Volume (liters)", xySeriesCollection);
// Get the XY Plot from the scatter chart
xyPlot = (XYPlot) chart.getPlot();
xyPlot.setDomainCrosshairVisible(true);
xyPlot.setRangeCrosshairVisible(true);
ValueAxis Xaxis = xyPlot.getDomainAxis();
Xaxis.setAutoRange(true);
Xaxis.setFixedAutoRange(80.0);
ValueAxis Yaxis = xyPlot.getRangeAxis();
Yaxis.setFixedAutoRange(6.0);
// Create the renderer
XYItemRenderer renderer = xyPlot.getRenderer();
renderer.setSeriesPaint(1, Color.blue);
NumberAxis domain = (NumberAxis) xyPlot.getDomainAxis();
domain.setVerticalTickLabels(false);
NumberAxis range = (NumberAxis) xyPlot.getRangeAxis();
range.setVerticalTickLabels(false);
chartPanel_1 = new ChartPanel(chart);
chartPanel_1.setZoomAroundAnchor(true);
chartPanel_1.setMaximumDrawHeight(700);
chartPanel_1.setRefreshBuffer(true);
chartPanel_1.setLocation(0, 0);
chartPanel_1.setSize(1200, 519);
chartPanel_1.setLayout(new BorderLayout(0, 0));
NumberAxis xAxis = (NumberAxis) xyPlot.getDomainAxis();
NumberAxis yAxis = (NumberAxis) xyPlot.getRangeAxis();
yAxis.setRange(-3.0, 4.0);
xyPlot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_LEFT);
xyPlot.setDomainAxisLocation(AxisLocation.BOTTOM_OR_LEFT);
return chartPanel_1;
}

JFreeChart Large Data Can't Read Axis

I am using JFreeChart to plot a line graph. The app reads in sensory data every 100 milliseconds so for a few minutes of capture it's a a lot of data. I don't plot the graph dynamically, it is static. I am using a Category plot since the axis can sometimes be decimal values, other times it can be strings, other times it can be boolean. My issue is the X axis (time) has so much data I can't make out the text:
Anyone know what I can do here to? Any tips or tricks to deal with this will be great!
private CategoryDataset createDataset() {
String series1 = "First";
String series2 = "Second";
String category1 = "Category 1";
String category2 = "Category 2";
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
for (int i = 0; i < time.size(); i++) {
dataset.addValue(Math.random(), series1, time.get(i));
}
return dataset;
}
private JFreeChart createChart(final CategoryDataset dataset) {
// create the chart...
final JFreeChart chart = ChartFactory.createLineChart(
"Line Chart Demo 6", // chart title
"Time", // x axis label
"RPM", // y axis label
dataset, // data
PlotOrientation.VERTICAL,
true, // include legend
true, // tooltips
false // urls
);
chart.setBackgroundPaint(Color.white);
final CategoryPlot plot = chart.getCategoryPlot();
plot.setBackgroundPaint(Color.white);
plot.setDomainGridlinePaint(Color.white);
plot.setRangeGridlinePaint(Color.white);
final CategoryItemRenderer renderer = (CategoryItemRenderer) plot.getRenderer();
plot.setRenderer(renderer);
return chart;
}
public void setLists(ArrayList<String> time) {
this.time = time;
final CategoryDataset dataset = createDataset();
final JFreeChart chart = createChart(dataset);
final ChartPanel chartPanel = new ChartPanel(chart);
chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
setContentPane(chartPanel);
}
You can turn off the Lables and TickMarks by adding:
CategoryPlot plot = (CategoryPlot) chart.getPlot();
CategoryAxis cx = new CategoryAxis();
cx.setTickLabelsVisible(false);
cx.setTickMarksVisible(false);
plot.setDomainAxis(cx);
If you wantto display a subset of the labels (every nth value) then you will need to subclass CategoryAxis so you can overide CategoryAxis#drawCategoryLabels() andCategoryAxis#drawTickMarks()

how to set first and last tick mark and x axis value in jfree bar chart x-axis

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);

how to get mouse's y or x axis coordinates in a jfreechart xy plot

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.

Categories

Resources