I am learning java and I am trying to build an app. I'm stuck with this one last part of the application and was hoping some of you may be able to help me. The application stores values in a database and, upon the users request, it will retrieve the data and plot this data on a line graph. The application is producing a line graph, but my issue is that it is producing one line graph for each piece of data that it retrieves from the database. So if the query returns 15 results, the application produces 15 graphs with one plot each. I want all of the data retrieved and plotted onto one graph. Below is my code. Can someone point me in the right direction?
try
{
Connection con = new DataConnection().connect();
ResultSet rs;
PreparedStatement retrieve = con.prepareStatement("SELECT row FROM table");
rs = retrieve.executeQuery();
while (rs.next())
{
String string = rs.getString(1);
double double = Double.parseDouble(string);
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
dataset.addValue(double, "Chart", "Data");
JFreeChart chart = ChartFactory.createLineChart("Graph", "Data", "Data", dataset, PlotOrientation.VERTICAL, true, false, false);
CategoryPlot p = chart.getCategoryPlot();
p.setRangeGridlinePaint(Color.black);
ChartFrame frame = new ChartFrame("Line Chart", chart);
frame.setVisible(true);
frame.setSize(450, 350);
}
}
So if the query returns 15 results, the application produces 15 graphs
with one plot each. I want all of the data retrieved and plotted onto
one graph.
Your code creates a new JFreeChart instance for each row in your database query result set and that's why you get too many frames with charts opened. You have to create just a single JFreeChart instance and add the data to its model as a series.
See this related Q&A: Multiple graphs in multiple figures using jFreeChart. There are also plenty of examples under jfreechart tag.
Related
I am monitoring CPU, RAM and disk IO for a computational pipeline that consists of multiple steps to process the input data. I would like to visualize the hardware consumption for the entire pipeline but also per step of the pipeline.
In order to render hardware consumptions, I'd like to draw a combined plot with jFreeChart with four vertically aligned subplots that all have the same x-axis - time. The top plot is supposed to be a gantt plot to indicate the step of the pipeline. In the second plot I'd like to render the CPU consumption over time. In the third plot the RAM consumption, the bottom plot is for disk IO. The aim is to visually slide horizontally over the plot and see, which step of the pipeline uses how much CPU, RAM and disk.
I'm all set up in eclipse, jFreeChart library installed and all my data is imported and ready to render. All I need is some guidance for how to set up the combined chart up, cause my code blows up, when I try to combine the Gantt plot (which is a category plot) and the CPU plot (which is XY plot):
public JFreeChart createChart() {
final JFreeChart ganttChart = ChartFactory.createGanttChart(
"Gantt of Tasks", // chart title
"Task", // domain axis label
"Time", // range axis label
createGanttDataset(), // data
true, // include legend
true, // tooltips
false // urls
);
JFreeChart cpuChart = ChartFactory.createTimeSeriesChart(
"CPU load", // title
"Time", // x-axis label
"CPU Load", // y-axis label
createCpuDataset(), // data
true, // create legend?
true, // generate tooltips?
false // generate URLs?
);
// parent plot...
final CombinedRangeCategoryPlot plot = new CombinedRangeCategoryPlot();
plot.setGap(10.0);
// add the subplots...
plot.add(ganttChart.getCategoryPlot(), 1);
plot.add(cpuChart.getCategoryPlot(), 1);
plot.setOrientation(PlotOrientation.VERTICAL);
// return a new chart containing the overlaid plot...
return new JFreeChart("Combined GANTT/CPU plot",
JFreeChart.DEFAULT_TITLE_FONT, plot, true);
}
private IntervalCategoryDataset createGanttDataset() {
final TaskSeries taskSeries = new TaskSeries("Tasks");
for (Map.Entry<DoubleLong, String> entry : algoStartEndDates.entrySet()) {
final String taskTitle = entry.getValue();
final long startDate = entry.getKey().n1;
final long endDate = entry.getKey().n2;
taskSeries.add(new Task(taskTitle, new SimpleTimePeriod(startDate, endDate)));
}
final TaskSeriesCollection collection = new TaskSeriesCollection();
collection.add(taskSeries);
return collection;
}
private XYDataset createCpuDataset() {
final TimeSeries timeSeries = new TimeSeries("CPU load");
for (CollectlData data : collectlData) {
final RegularTimePeriod t = new Millisecond(new Date(data.getUtcTime()));
timeSeries.add(t, data.getCpuData().getTotal());
}
final TimeSeriesCollection dataset = new TimeSeriesCollection();
dataset.addSeries(timeSeries);
dataset.setDomainIsPointsInTime(true);
return dataset;
}
I would expect this to create a combined plot, but I'm receiving the error message:
Caused by: java.lang.ClassCastException: class org.jfree.chart.plot.XYPlot cannot be cast to class org.jfree.chart.plot.CategoryPlot (org.jfree.chart.plot.XYPlot and org.jfree.chart.plot.CategoryPlot are in unnamed module of loader 'app')
at org.jfree.chart.JFreeChart.getCategoryPlot(JFreeChart.java:824) ~[jfreechart-1.0.15.jar:1.0.15]
I want to create a chart using mysql database with Jfreechart, this is the code i used :
try {
String query =
"Select id,Prop_menages_Urbains_Proprietaires from fes";
JDBCCategoryDataset dataset =
new JDBCCategoryDataset(
DBConnection.DBConnection(),
query
);
JFreeChart chart =
ChartFactory.createBarChart(
"test",
"id",
"Prop_menages_Urbains_Proprietaires",
dataset,
PlotOrientation.VERTICAL,
false,
true,
true
);
BarRenderer render = null;
CategoryPlot plot = null;
render = new BarRenderer();
ChartFrame fram =
new ChartFrame("test", chart);
fram.setVisible(true);
fram.setSize(600,650);
}
catch(Exception ex) {
System.out.println("Erreur: " + ex);
}
after the execution the barchart doesn't show up although there are no errors in the code syntax
any help please ?
UPDATE: i tried the same code but this time i used other columns from the database and it worked , what's the issues with the other one knowing that they're all numbers
The JDBCCategoryDataset API specifies:
The SQL query must return at least two columns. The first column will be the category name and remaining columns values (each column represents a series).
This complete example, which you have successfully adapted, illustrates the effect. The question then becomes,
What's the issues with the other one knowing that they're all numbers?
The executeQuery() source shows how each of the java.sql.Types is mapped to a numeric value: a numeric type becomes a Number directly, a date type becomes a Number representing milliseconds from the Java epoch, and a character type is converted using Double.valueOf(); the default is null.
In this case, verify that Prop_menages_Urbains_Proprietaires has a SQL type that is suitable for conversion to a numeric value.
I'm currently using JFreeChart to create a line chart. This line chart gets updated every second with a new value (currently a random value). This way you can see how your data has changed over a certain time period. However after I've added over ten values they don't fit on the line anymore turning into dots. I would like to only have 5 values shown at a time which are spread across the entire timings. This is how it looks now:
Notice the dots at the bottom of the chart. I would like it to be changed to this:
Note that I want to keep all points which are created between these points in time. So data from 11:31:00, 11:31:01, 11:31:02 etc. should be still there.
This is what I currently have:
LocalDateTime date = LocalDateTime.now();
category = new DefaultCategoryDataset();
category.addValue(new Random().nextInt(10), "Data", date.getHour() + ":" + date.getMinute() + ":" + date.getSecond());
chart = ChartFactory.createLineChart("Values", "Time", "Data", category, PlotOrientation.VERTICAL, false, true, false);
((NumberAxis) ((CategoryPlot) chart.getPlot()).getRangeAxis()).setStandardTickUnits(NumberAxis.createIntegerTickUnits());
I got it by using a TimeSeriesChart. This is what I ended up with:
TimeSeriesCollection collection = new TimeSeriesCollection();
TimeSeries serie = new TimeSeries("Data");
collection.addSeries(serie);
JFreeChart chart = ChartFactory.createTimeSeriesChart("Data", "Time", "Data", collection, false, true, false);
I am new to Jfreechart. I am creating a 3d pie chart in jfreechart and adding this to pdf using itext api. I am able to generate 3d pie chart dynamically and the tool tip for the pie chart too. I am displaying the plot tool tip in percentage. But for the value that is less then 1, the plot is not getting generate.
Please anyone help me to sort this problem.
Edit: Here is my dataset:
final DefaultPieDataset result = new DefaultPieDataset();
result.setValue("Java", new Double(43.2));
result.setValue("Visual Basic", new Double(10.0));
result.setValue("C/C++", new Double(17.5));
result.setValue("PHP", new Double(32.5));
result.setValue("Perl", new Double(1.0));
result.setValue("dotnet", new Double(0.04));
result.setValue("python", new Double(1.06));
result.setValue("cobol", new Double(0.08));
Pie plot is not getting generated for "dotnet" and "cobol".
I have a question about a JFreeChart issue. I want to display a chart with a line from the values out of my database. This is the code I have now:
public void drawachart(){
try{
String sql= "select status,date from luggage";
JDBCCategoryDataset dataset = new JDBCCategoryDataset(
"jdbc:mysql://localhost/corendon", "com.mysql.jdbc.Driver", "root", "root");
dataset.executeQuery(sql);
JFreeChart chart = ChartFactory.createLineChart("chart","date", "status",
dataset,PlotOrientation.VERTICAL,false,true,true);
BarRenderer bar= null;
bar = new BarRenderer();
CategoryPlot plot =null;
ChartFrame frame = new ChartFrame("shart", chart);
frame.setVisible(true);
frame.setSize(500, 500);
}
catch(Exception e){
e.printStackTrace();
}
}
After executing the code, it gives me a chart with no lines in it. Only a x and y axis. What should I do to get a line in the chart.
Try JDBCXYDataset, mentioned here. Because "the first column will be the x-axis," change your query to "select date, status from luggage". JDBCXYDataset can detect a time series based on metadata, so ChartFactory.createTimeSeriesChart() may be a suitable choice.