How to display database values in JFreeChart linechart - java

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.

Related

Add Regression Line using Java and mysql [duplicate]

This question already has answers here:
Plotting multiple regression lines through different Y-Intercepts and X-values
(1 answer)
How can I get a values from the line chart in java?
(1 answer)
Closed 4 years ago.
I'm a beginner in Java. I would like to ask if is it possible to add a regression line in line chart using java and mysql? anyway this is my code:
try {
String sql = "select YEAR(admission.admissiondate) as YEAR, count(admissionID) as StudNum from admission group by YEAR(admissiondate)";
JDBCXYDataset dataset = new JDBCXYDataset(
"jdbc:mysql://localhost/zoom", "com.mysql.jdbc.Driver", "root", "");
dataset.executeQuery(sql);
final JFreeChart chart = ChartFactory.createXYLineChart ("Number of Students Per Year","YEAR", "Number of Students",
dataset,PlotOrientation.VERTICAL,true,true,false);
XYPlot plot =null;
ChartFrame frame = new ChartFrame("cchart", chart);
frame.setVisible(true);
frame.setSize(500, 500);
chart.setBackgroundPaint(Color.white);
XYPlot xyPlot = chart.getXYPlot();
NumberAxis domainAxis = (NumberAxis) xyPlot.getDomainAxis();
domainAxis.setTickUnit(new NumberTickUnit(1.0));
domainAxis.setRange(2016,2030);
} catch(Exception e) {
e.printStackTrace();
}
You can find a Regression Class in the
JFree API which basically does what it sounds like.
A more detailed Example is shown here under
'Adding a Regression line to the Graph':
private void drawRegressionLine() {
// Get the parameters 'a' and 'b' for an equation y = a + b * x,
// fitted to the inputData using ordinary least squares regression.
// a - regressionParameters[0], b - regressionParameters[1]
double regressionParameters[] = Regression.getOLSRegression(inputData,
0);
// Prepare a line function using the found parameters
LineFunction2D linefunction2d = new LineFunction2D(
regressionParameters[0], regressionParameters[1]);
// Creates a dataset by taking sample values from the line function
XYDataset dataset = DatasetUtilities.sampleFunction2D(linefunction2d,
0D, 300, 100, "Fitted Regression Line");
// Draw the line dataset
XYPlot xyplot = chart.getXYPlot();
xyplot.setDataset(1, dataset);
XYLineAndShapeRenderer xylineandshaperenderer = new XYLineAndShapeRenderer(
true, false);
xylineandshaperenderer.setSeriesPaint(0, Color.YELLOW);
xyplot.setRenderer(1, xylineandshaperenderer);
}

Barchart is connected to each other but I need it to be separate

Everything seems to be working fine, the only problem is that the chart is supposed to be produced is a bar chart that is not connected to each other, however the chart I ended up with is not the one I intended for.
I followed a video and the code seemed to be similar, so I can't figure out what went wrong:
try {
int rubyPoints = Integer.parseInt(getHP("Ruby"));
int amberPoints = Integer.parseInt(getHP("Amber"));
int pearlPoints = Integer.parseInt(getHP("Pearl"));
int sapphirePoints = Integer.parseInt(getHP("Sapphire"));
DefaultCategoryDataset barChartData = new DefaultCategoryDataset();
barChartData.setValue(rubyPoints, "House Points", "Ruby");
barChartData.setValue(amberPoints, "House Points", "Amber");
barChartData.setValue(pearlPoints, "House Points", "Pearl");
barChartData.setValue(sapphirePoints, "House Points", "Sapphire");
JFreeChart barChart = ChartFactory.createAreaChart("House Points",
"All houses", "Amount of points", barChartData, PlotOrientation.VERTICAL, false, true, false);
CategoryPlot barchrt = barChart.getCategoryPlot();
barchrt.setRangeGridlinePaint(Color.BLUE);
ChartPanel barPanel = new ChartPanel(barChart);
panelChart.removeAll();
panelChart.add(barPanel, BorderLayout.CENTER);
panelChart.validate();
} catch (IOException ioe) {
// error handling
}
The chart looks like this (which is not what I need it to look like):
This is very simple: the chart you've created is not a barChart, but an areaChart.
In order to get the result you want, just change the line where instantiating the chart to:
JFreeChart barChart = ChartFactory.createBarChart("House Points",
"All houses", "Amount of points", barChartData, PlotOrientation.VERTICAL, false, true, false);
And you'll get something like:

Problems plotting jFreechart with array

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.

Plotting a hysteresis loop with jFreeChart

I need to draw hysteresis loops and then calculate the area closed within the loop. I am using jFreeChart.
consider the following data:
hyst[0]=0;
hyst[1]=0;
hyst[2]=0.0098;
hyst[3]=0.0196;
hyst[4]=0.0489;
hyst[5]=0.0879;
hyst[6]=0.0684;
hyst[7]=0.0489;
hyst[8]=0.0196;
hyst[9]=0.0098;
hyst[10]=0;
hyst[11]=0;
hyst[12]=0;
hyst[13]=0;
hyst[14]=0;
hyst[15]=-0.0195;
hyst[16]=-0.0488;
hyst[17]=-0.0391;
hyst[18]=-0.0195;
hyst[19]=0;
hyst[20]=0;
When I try :
public void plotHysteresis()
{
int j=0;
int i=0;
XYSeries series1 = new XYSeries("Before Treatment");
// DefaultCategoryDataset series1 = new DefaultCategoryDataset();
for(i=0;i<6;i++)
{
series1.add(j,hyst[i]);
logTextArea.append(Integer.toString(j) +" : " +Double.toString(hyst[i])+"\n");
j=j+5;
}
j=j-5;
for(;i<11;i++)
{
j=j-5;
series1.add(j,hyst[i]);
logTextArea.append(Integer.toString(j) +" : " +Double.toString(hyst[i])+"\n");
}
for(;i<16;i++)
{
j=j-5;
series1.add(j,hyst[i]);
logTextArea.append(Integer.toString(j) +" : " +Double.toString(hyst[i])+"\n");
}
for(;i<21;i++)
{
j=j+5;
series1.add(j,hyst[i]);
logTextArea.append(Integer.toString(j) +" : " +Double.toString(hyst[i])+"\n");
}
XYSeriesCollection dataset = new XYSeriesCollection();
dataset.addSeries(series1);
JFreeChart chart = ChartFactory.createXYAreaChart(
"Hysteresis Plot", // chart title
"Pounds (lb)", // x axis label
"Distance (inches)", // y axis label
dataset, // data
PlotOrientation.VERTICAL,
true, // include legend
true, // tooltips
false // urls
);
chart.setBackgroundPaint(Color.white);
ChartPanel frame = new ChartPanel(chart);
frame.setVisible(true);
frame.setSize(plotPanel.getWidth(),plotPanel.getHeight());
plotPanel.add(frame);
plotPanel.repaint();
}
It gives me below result:
If I use :
JFreeChart chart = ChartFactory.createXYLineChart(
"Hysteresis Plot", // chart title
"Pounds (lb)", // x axis label
"Distance (inches)", // y axis label
dataset, // data
PlotOrientation.VERTICAL,
true, // include legend
true, // tooltips
false // urls
);
I gives:
I need a hysteresis plot that looks like:
I guess the difference is the way points are being connected. Please guide how to obtained the desired hysteresis loop with jFreeChart and then how to calculate area enclosed.
Thanks
How can I change the line color as well the symbols representing the data points. I want all of them to be uniform.
It appears you've settled on JFreeChart for your view. Synthesizing a few other comments,
You can make the colors and shapes of your several series homogeneous by providing a DrawingSupplier, as suggested here and shown here.
You can combine the series into a GeneralPath and estimate the area as outlined here.

Display percentage value in Pie Chart

I did the coding to create a pie chart file in png format file; the pie chart shows the percentage, but it's in the bottom of the file. I want the percentage to appear in the chart itself. This is the code I have used:
String query = "SELECT name,flag from mawarid";
JDBCPieDataset dataset = new JDBCPieDataset(
"jdbc:oracle:thin:# 127.0.0.1:1521:XE", "oracle.jdbc.OracleDriver", "", "");
dataset.executeQuery(query);
JFreeChart chart = ChartFactory.createPieChart(
"Test", dataset, true, true, false);
try {
PiePlot plot = (PiePlot) chart.getPlot();
plot.setLegendLabelGenerator(
new StandardPieSectionLabelGenerator("{0} {2}"));
final ChartRenderingInfo info = new ChartRenderingInfo(
new StandardEntityCollection());
final File file1 = new File("Chart5.png");
ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info);
} catch (Exception e) {
// log exception
}
You can use the same message format in a label generator as you do in your legend label generator:
plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0} {2}"));
Try using PieLabelDistributor on the PiePlot.
plot.setLabelDistributor(PieLabelDistributor aDistributor)

Categories