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)
Related
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);
}
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:
Im trying to change the background color to my bar chart and so far nothing seems to be working
Here is my code below:
JFreeChart expbarchart = ChartFactory.createBarChart("Monthly Expenditures", "Expenditure Type", "Amount (£)", barexp, PlotOrientation.VERTICAL, false, true, false);
ChartPanel expframe = new ChartPanel(expbarchart);
expframe.setLocation(695, 49);
expframe.setSize(641,500);
expframe.setBorder(new EtchedBorder(EtchedBorder.LOWERED, new Color(173, 216, 230), null));
graphpanel.add(expframe);
I have tried doing .setbackground() and it does not seem to work
Thanks
BarChartDemo1 shows you how to set the chart background paint:
chart.setBackgroundPaint(new Color(173, 216, 230));
It also shows you how to set a ChartTheme that you can change:
StandardChartTheme theme = new StandardChartTheme("JFree/Shadow", true);
Color color = new Color(173, 216, 230);
theme.setPlotBackgroundPaint(color);
theme.setChartBackgroundPaint(color.brighter());
ChartFactory.setChartTheme(theme);
try this and customize as per your need.
// create the chart...
JFreeChart chart = ChartFactory.createLineChart(
"# of Sales by Month", // chart title
"Month", // domain axis label
"# of Sales", // range axis label
dataset, // data
PlotOrientation.VERTICAL, // orientation
true, // include legend
true, // tooltips
false // urls
);
if(subTitle != null && !subTitle.isEmpty())
chart.addSubtitle(new TextTitle(subTitle));
chart.setBackgroundPaint(Color.BLUE);
// Paint p = new GradientPaint(0, 0, Color.white, 1000, 0, Color.green);
// chart.setBackgroundPaint(p);
CategoryPlot plot = (CategoryPlot) chart.getPlot();
plot.setRangePannable(true);
plot.setRangeGridlinesVisible(true);
plot.setBackgroundAlpha(1);
plot.setBackgroundPaint(Color.BLUE);
// Paint p = new GradientPaint(0, 0, Color.white, 1000, 0, Color.green);
// plot.setBackgroundPaint(p);
NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
ChartUtilities.applyCurrentTheme(chart);
You have to use JFreeChart.getPlot().setBackgroundPaint(Color.XXXXXX); like this:
public static void main(String[] args) {
DefaultPieDataset pieDataset = new DefaultPieDataset();
pieDataset.setValue("LoggedIn" +": "+ 5, 10);
pieDataset.setValue("LoggedOut" +": "+ 8, 17);
JFreeChart jfc = ChartFactory.createPieChart("title", pieDataset, false, false, false );
jfc.getPlot().setBackgroundPaint(Color.BLUE);
ChartPanel chart = new ChartPanel(jfc);
JFrame frame = new JFrame();
frame.add(chart);
frame.pack();
frame.setVisible(true);
}
Of course, you can catch the desired color by several different methods regarding your needs, for example:
Color color1 = "anyComponent".getBackgroundColor();
and then apply
jfc.getPlot().setBackgroundPaint(color1);
I hope it helps!
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.
i need the following type of chart:
It should be a "steped" line chart with categories on the vertical axis, like this:
I found this example of an Category Step Chart, but it the orientation is not right for my purpose.
http://www.jfree.org/jfreechart/api/javadoc/org/jfree/chart/renderer/category/CategoryStepRenderer.html
All i have done so far is this, but as you can see the red line does not fit to the orientation of the chart(should be horizontal):
The corresponding code to this:
DefaultCategoryDataset ds = new DefaultCategoryDataset();
// create dataset
for (int k = 0; k < ffCount; k++) {
StateSignal ss1 = (StateSignal) this.ffDSet.getFframes().get(k).getSignals().get(i);
ds.setValue((double) k + 1, ss1.getName(), ss1.getStates().get(0).getStatus());
}
CategoryStepRenderer categorysteprenderer = new CategoryStepRenderer(false);
categorysteprenderer.setBaseToolTipGenerator(new StandardCategoryToolTipGenerator());
CategoryAxis categoryaxis = new CategoryAxis("Category");
NumberAxis numberaxis = new NumberAxis("Value");
CategoryPlot categoryplot = new CategoryPlot(ds, categoryaxis, numberaxis, categorysteprenderer);
categoryplot.setRangePannable(true);
categoryplot.setOrientation(PlotOrientation.HORIZONTAL);
chart = new JFreeChart("test", null, categoryplot, true);
I don´t get it to work. Any ideas?
Thanks in advance!
It looks like you need to use a standard XYLineChart with a XYStepRenderer and a SymbolAxis to replace the default Range Axis rather than a CategoryStepRenderer and a horizontal plot orientation
If you associate Status A and B with a numerical value say 1 and 2 you can create a chart like this:
Using this a XYStepRenderer
XYStepRenderer renderer = new XYStepRenderer();
renderer.setBaseShapesVisible(true);
renderer.setSeriesStroke(0, new BasicStroke(2.0f));
renderer.setSeriesStroke(1, new BasicStroke(2.0f));
renderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator());
renderer.setDefaultEntityRadius(6);
plot.setRenderer(renderer);
and a Symbol Axis
String[] grade = new String[3];
grade[0] = "";
grade[1] = "Status A";
grade[2] = "Status B";
SymbolAxis rangeAxis = new SymbolAxis("", grade);
rangeAxis.setTickUnit(new NumberTickUnit(1));
rangeAxis.setRange(0,3);
plot.setRangeAxis(rangeAxis);
In this example the SymbolAxis provides an alternative label for each value in the Axis