Today I just start to learn JFreeChart only and this is my code`
try{
String query = "Select Purchase_Date,Total_Quantity_Purchased "
+ "from Purchases";
JDBCCategoryDataset dataset = new JDBCCategoryDataset(javaconnect.ConnecrDb(),query);
JFreeChart chart = ChartFactory.createLineChart("Chart", "Purchase Date", "Total Purchase", dataset, PlotOrientation.VERTICAL, false, true, true);
BarRenderer renderer = null;
CategoryPlot plot = null;
renderer = new BarRenderer();
ChartFrame frame = new ChartFrame("Title",chart);
frame.setVisible(true);
frame.setSize(500,650);
}catch(Exception ex){
JOptionPane.showMessageDialog(null,ex.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
}
and my result is listing out all of my database's data.
And now I want to improve it , I want to search total purchase on specific date
Example from july 1 to july 10 . Is there anyway to do this?? I am new to this. Please help. TQ
Edit :
java.util.Date utilStartDate = from.getDate();
java.sql.Date sqlStartDate = new java.sql.Date(utilStartDate.getTime());
java.util.Date utilStartDate2 = to.getDate();
java.sql.Date sqlStartDate2 = new java.sql.Date(utilStartDate2.getTime());
String query = "Select Purchase_Date, Total_Purchase_Quantity from Purchasing Where Purchase_Date between "+sqlStartDate+" and "+sqlStartDate2+"";
JDBCXYDataset dataset = new JDBCXYDataset (javaconnect.ConnecrDb(),query);
JFreeChart chart = ChartFactory.createTimeSeriesChart("Query chart", "Date", "Total Order", dataset, true,true,false);
BarRenderer renderer = null;
CategoryPlot plot = null;
renderer = new BarRenderer();
ChartFrame frame = new ChartFrame("Query Chart",chart);
frame.setVisible(true);
frame.setSize(500,650);
Error give me not enough valid columns where generate by query
Since your query looks at quantity for a range of dates, you might want to consider JDBCXYDataset, mentioned here, "which can detect a time series based on metadata;" use it with a time series chart, ChartFactory.createTimeSeriesChart().
Addendum; It give me error: "Not enough valid columns [were] generated by query." What does it mean?
It's hard to say without a complete example & schema, but you can check your query against the recognized java.sql.Types.
Related
Currently I'm working on charts and want to achieve an output.
I wanted to achieve two things.
To display candle stick chart of stocks data. [done]
To display the stock split log above or below the candle. [pending]
I'm using JFreeChart SDK to build the charts.
I'm using OHLCDataItem[] to build data for daily high/low etc of stock. unfortunately jfreechart does not have any extension of OHLCDataItem to show additional information (logo + text metadata) on the candle.
Sample code:
TimeSeries timeSeriesDailyMovingAverage = new TimeSeries("day moving average");
List<OHLCDataItem> dataItems = new ArrayList<OHLCDataItem>(); //to collect High low close prices
OHLCDataItem item = new OHLCDataItem(date, open, high, low, adjClose, volume);//this code is in loop with do that more data can be added for each day
dataItems.add(item);
OHLCDataItem[] data = dataItems.toArray(new OHLCDataItem[dataItems.size()]);
OHLCDataset dataset = new DefaultOHLCDataset(symbol, data);
//now initializing the candleStickRanderer and setting its properties series strock + paint
CandlestickRenderer CandleStickRenderer = new CandlestickRenderer();
XYLineAndShapeRenderer LineRenderer = new XYLineAndShapeRenderer(true, false);
HighLowRenderer OHLCRenderer = new HighLowRenderer();
DateAxis domainAxis = new DateAxis();
NumberAxis rangeAxis = new NumberAxis();
rangeAxis.setStandardTickUnits(NumberAxis.createStandardTickUnits());
XYPlot plot = new XYPlot(dataset, domainAxis, rangeAxis, LineRenderer);//set other properties
JFreeChart chart = new JFreeChart(info, new Font("SansSerif", Font.PLAIN, 15), plot, false);
ChartPanel chartPanel = new ChartPanel(chart);
JPanel panel = new JPanel(new BorderLayout());
panel.add(chartPanel, BorderLayout.CENTER);
getContentPane().add(panel);
XYPlot xyplot = (XYPlot) chart.getPlot();
xyplot.setRenderer(CandleStickRenderer);
This is some rough code which is working fine. I'm getting the desired out of Candle chart.
current output of candle stick
But I cannot figure out how can I add text/logo on XYPlot based on dataset.
What I want to achieve is that, add text/or shape containing text information at the bottom/top of a particular candle.
It would be a great help if someone can guide me how I can do it based on the dataset.
The desired output is like this chart.
desired output
Or
desired output
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.
I want to create a stacked bar chart with line graph on it using jfreechart by taking values from db.
Basically, I want to show two values on the bar - failed values and success values on top of that.
A line graph will touch all the bars and its value will be the summation of failed and success values for that respective hour.
Also, I want one horizontal line which will represent the average of all the values , i.e. total count of (failed+success) values
This Stacked Bar will have per hour values , i.e on the x-axis hours count will be present.
Y -axis should have no. of values.
I have written the following code for creating only StackedBarChart, but its not generating the graph
As I am new to jfreechart, I am not sure how to come up with the code. Any help would be appreciated.
code.....
String query1 = "select * from table1";
ps = con.prepareStatement(query1);
rs = ps.executeQuery();
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
System.out.println("Creating Graph of hourly count");
while (rs.next())
{
Number a = Long.parseLong(rs.getString("SuccessValues"));
String b = rs.getString("FailureValues");
String c = rs.getString("Hours");
dataset.setValue(a, b, c);
}
final String title = "Per Hour Count";
final String Xaxis = "Time";
final String Yaxis = "Orders";
barChartDisp(title,Xaxis,Yaxis,dataset);
private void barChartDisp(String title, String xaxis, String yaxis, DefaultCategoryDataset dataset) {
try{
JFreeChart barChart = ChartFactory.createStackedBarChart(title, xaxis, yaxis, dataset,
PlotOrientation.VERTICAL, true, true, false);
int width = 640;
int height = 480;
File BarChart = new File("BarChart.jpeg");
ChartUtilities.saveChartAsJPEG(BarChart, barChart, width, height);
}}
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 faced with a problem of putting date on my JFreeChart graph.
I read the double value and date value from my local MySql database but I cannot put date onto the graph.
Here is my useless tryings
XYSeries series = new XYSeries("Dynamic");
for (int i = 0; i < ch.size(); i++) {
series.add(ch.get(i) * * *.get_date() * * *
,ch.get(i).get_pro());
}
XYDataset xyDataset = new XYSeriesCollection(series);
JFreeChart chart = ChartFactory.createXYLineChart("Title", "Date", "Buy",
xyDataset,
PlotOrientation.VERTICAL,
true, true, true);
JFrame add = new DynamicCurrency(ch);
add.getContentPane().add(new ChartPanel(chart));
add.setVisible(true);
I bold the place where the mistake occurs.
Thanks a lot
You can use the getTime() method which returns a long and cast it to double:
series.add((double) ch.get(i).get_date().getTime(), ch.get(i).get_pro());