I have a data source in which there are three departments and each department has equal employees that are 8.
I want to make a pie chart using jFreeChart such that first we partition the pie into 3 equal parts for departments that is 120' for each department. Then in these partitions I want to show the sales of each employee. How can I do this in jFreeChart.
public class PieChart extends JFrame {
private PieDataset createDataset() {
DefaultPieDataset result = new DefaultPieDataset();
result.setValue("department1", 33.33);
result.setValue("department2", 33.33);
result.setValue("department3", 33.33);
return result;
}
private JFreeChart createChart(PieDataset dataset, String title) {
JFreeChart chart = ChartFactory.createPieChart3D(title, // chart title
dataset, // data
true, // include legend
true,
false);
PiePlot3D plot = (PiePlot3D) chart.getPlot();
plot.setStartAngle(290);
plot.setDirection(Rotation.CLOCKWISE);
plot.setForegroundAlpha(0.5f);
return chart;
}
}
public static void main(String[] args) {
PieChart demo = new PieChart("Comparison", "Which operating system are you using?");
demo.pack();
demo.setVisible(true);
}
PieChartDemo1 is a good starting point; focus on createDataset(); the full source is included in the distribution.
Addendum: How to further create partitions?
Ah, you want to sub-divide each 120° partition. DefaultPieDataset doesn't support a hierarchical structure directly, but you can use color in the PiePlot to highlight the grouping. Create related colors using Color.getHSBColor(), as shown here, and use setSectionPaint() to apply the colors accordingly.
Related
I have to implement an histogram using JFreeChart API. This histogram has to represent the datas of this JTable:
So I have a JTable with three columns: "thea", "type", "Number of occurrences". My histogram has two targets: the first is to count the number of occurrences of each thea field; the second is to mark with different colors the bars corresponding to JTable records with different types.
To implement my histogram I used a DefaultCategoryDataset:
private DefaultCategoryDataset createDataset(ArrayList<String>fieldsOccs) {
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
for(int i = 0; i<this.fieldsOccs.size() && i<end; i++) {
String thea = fieldsOccs.get(i).getFieldName();
String type = fieldsOccs.get(i).getType();
int occurrences = fieldsOccs.get(i).getOccurrences();
dataset.setValue(occurrences, type, thea);
}
return dataset;
}
Anf then I create my chart using a createChart method:
private JFreeChart createChart(DefaultCategoryDataset dataset) {
JFreeChart chart = ChartFactory.createBarChart(
"",
"", //X-axis title
"", //Y-axis title
dataset, //dataset
PlotOrientation.HORIZONTAL, //plot orientation
true, //show legends
true, //use tooltips
false //generate URLs
);
return chart;
}
This is what I get:
As you can see in the picture it is not nice to see. The values on x axes are not formatted correctly.
How can I solve this rendering problem?
--edit
I have this problem just in case of more types in the JTable. For example if my JTable is:
and there is just String, the correspondig histogram is nice:
--edit1
What dou you think about StackedBarChart3D? I get this output:
My histogram has two targets:
You may get a more appealing result with ChartFactory.createHistogram() and a SimpleHistogramDataset, seen here.
To get diverse colors, override the getItemPaint() method in a custom XYBarRenderer, as suggested here.
The spider web plot of JFreeChart does not display values close to the marked points, as default:
what must be done to display the numbers?
That's what I have now, in a method returning StreamedContent (for PrimeFaces' p:graphicImage:
CategoryDataset categorydataset = createCategoryDataset(displayBy, configuration, null);
SpiderWebPlot plot = new SpiderWebPlot(categorydataset);
plot.setInteriorGap(0.40);
plot.setNoDataMessage("No data available");
plot.setStartAngle(0);
plot.setLabelGenerator(new StandardCategoryItemLabelGenerator("{2}", NumberFormat.getInstance()));
plot.setWebFilled(true);
JFreeChart chart = new JFreeChart(title, TextTitle.DEFAULT_FONT, plot, true);
File chartFile = new File(String.valueOf(new Random().nextLong()));
ChartUtilities.saveChartAsPNG(chartFile, chart, 375, 300);
return new DefaultStreamedContent(new FileInputStream(chartFile), "image/png");
EDIT: After #trashgod's suggestion, some values appeared but no in the expected place. I want the columnKey values, not the `rowKey' values (addValue method in DefaultCategoryDataset class):
What must be done to display the numbers?
You can label points on the plot using a CategoryItemLabelGenerator, as shown here.
What matters are the three other [points].
It looks like you might be able to add a second series, one with a second rowKey, in order to get labels associated with those points.
First off, I am new to Java and to Stackoverflow. So I hope I can supply enough clarity in my question.
My goal is to create a box plot using jfreechart to keep track of measurement values from every day use. I want to do this by storing minimal amount of data ie. by storing statists of mean, standard deviation, median, 1Q,3Q, min and maximum. This should then be visualized by a box plot for each day measured.
I have looked at the box plot demo here
http://www.java2s.com/Code/Java/Chart/JFreeChartBoxAndWhiskerDemo.htm
In this demo they create the dataset and add all the values to the dataset, then adds it to the plot. The dataset itself contains methods to return the mean, median etc. of the dataset to be able to create the plot. See the code below for a snip from the demo in the link above.
DefaultBoxAndWhiskerCategoryDataset dataset = new DefaultBoxAndWhiskerCategoryDataset();
//some type of algorithm to add values to the dataset
dataset.add(//values, series and type here);
// Return the finished dataset
CategoryAxis xAxis = new CategoryAxis("Type");
NumberAxis yAxis = new NumberAxis("Value");
yAxis.setAutoRangeIncludesZero(false);
BoxAndWhiskerRenderer renderer = new BoxAndWhiskerRenderer();
renderer.setFillBox(false);
renderer.setToolTipGenerator(new BoxAndWhiskerToolTipGenerator());
CategoryPlot plot = new CategoryPlot(dataset, xAxis, yAxis,
renderer);
JFreeChart chart = new JFreeChart("Box-and-Whisker Demo",
new Font("SansSerif", Font.BOLD, 14), plot, true);
So my question is, how should I do to just add the median, Q1,Q3, mean, minimum and maximum values to create the box plot? Because in the demo above they base the plot of a complete sample set.
You can create your own dataset class and use it to create the chart.
Create your own implementation of BoxAndWhiskerCategoryDataset and use it in place of DefaultBoxAndWhiskerCategoryDataset.
I am making use of the JFreeChart library to plot the progress of a genetic algorithm in real time.
I'm using Swing for the UI. I have a panel where I draw all the various parameters for the algorithm, and a ChartPanel object. This object is drawn before I call the algorithm's search method (which updates the chart's XYSeries object at each generation), and at the end of the search, with all the values being accurately plotted.
According to the docs, the ChartPanel object is redrawn when its respective chart is updated. Obviously, the Swing panel itself isn't being redrawn until after the search is done, and I call repaint(), but what can I do to fix this?
This is the chart code:
public class XYSeriesDemo {
private static final long serialVersionUID = 1L;
private XYSeries series;
private JFreeChart chart;
public XYSeriesDemo(String str) {
series = new XYSeries(str);
XYSeriesCollection data = new XYSeriesCollection(series);
chart = createChart(data);
}
public XYSeries getSeries() {
return series;
}
public ChartPanel getChartPanel() {
return new ChartPanel(chart);
}
private JFreeChart createChart(final XYDataset data) {
JFreeChart chart = ChartFactory.createXYLineChart(
"Best fitness across generations",
"Generation",
"Fitness",
data,
PlotOrientation.VERTICAL,
true,
true,
false
);
XYPlot plot = chart.getXYPlot();
ValueAxis axis = plot.getDomainAxis();
axis.setAutoRange(true);
axis = plot.getRangeAxis();
axis.setAutoRange(true);
return chart;
}
}
In my panel constructor, I'm doing the following (this gets an empty chart drawn):
demo = new XYSeriesDemo("Best fitness");
this.add(demo.getChartPanel());
This is the method that the Swing frame calls in my JPanel object when the user orders a search:
public void solve() {
gen = new Random(seed);
XYSeries s = demo.getSeries();
GeneticAlgorithm ga = new GeneticAlgorithm(pop, crossoverP, mutationP,
eliteSize, maxGens, gen, s);
best = ga.search();
state = State.SOLVED;
time = ga.getTime() / 1E9;
}
At each generation, the search method in the algorithm simply does:
series.add(generation, pop.getBestFitness());
Thank you for reading.
Make sure that you are updating the dataset or series for the chart, ideally directly. The chart should refresh itself.
I would recommend buying the JFreeChart developer guide as it includes all sorts of examples including dynamic charts. The cost of the developer guide is what supports JFreeChart development.
I think you call your search process in EDT because of that it can't repaint components.
For updating your panel from code try to use SwingWorker, it can update UI and continue background process. You can find a lot of examples of using in Internet.
Or you can try to use Executors for background search process and updating UI.
I think this will work for you
JFreeChart jf = // Your JFreeChart chart Object.
ChartPanel chartPanel = new ChartPanel(jf);
myPanel.add(chartPanel);
myPanel.repaint();
myPanel.revalidate();
How can I draw such a graph using Swing? I have used a JFreeChart library, but I don't know how can I draw such a line graph using that library?
import org.jfree.chart.*;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.xy.*;
public class DrawGraph{
public void drawGraph(int[][] drawPoints) {
XYSeries series = new XYSeries("Average Weight");
for(int i=0;i<drawPoints.length;i++){
for(int j=0;j<=1;j+=2){
if(drawPoints[i][j]!=0){
series.add(bla...bla...bla...);
}
}
}
XYDataset xyDataset = new XYSeriesCollection(series);
JFreeChart chart = ChartFactory.createXYLineChart
("XYLine Chart using JFreeChart", "Age", "Weight",
xyDataset, PlotOrientation.VERTICAL, true, true, false);
ChartFrame frame1=new ChartFrame("XYLine Chart",chart);
frame1.setVisible(true);
frame1.setSize(300,300);
}
}
I have drawn graph using this but isn't working...
It looks like you're having trouble constructing a dataset. You can use a method like that shown below with either ChartFactory.createXYAreaChart() or ChartFactory.createXYLineChart().
private static XYDataset createDataset() {
XYSeriesCollection result = new XYSeriesCollection();
XYSeries series = new XYSeries("Test");
series.add(0, 2);
// more points here
series.add(10, 10);
result.addSeries(series);
return result;
}
See also these examples.
As an aside, it's not clear what's important in you picture, and I can't make sense of the unordered axis at the top. In my opinion, the better question is not How do I make this graph? but rather How can I best display this data?
http://sourceforge.net/apps/trac/jung/wiki/JUNGManual
Use JUNG instead. Its easy and written in java.