JFreeChart — Tutorial
JFreeChart is a free 100% Java chart library created by David Gilbert. JFreeChart makes it easy for developers to display professional quality charts in their applications. For details on JFreeChart please check the following link: http://www.jfree.org/jfreechart/.
2. Download JFreeChart
Download the JFreeChart distribution from the website http://www.jfree.org/jfreechart/.
3. Creating Pie Charts with JFreeChart
3.1. Create Project
Create a new Java project «de.vogella.jfreechart.swing.pie». Create also a package «de.vogella.jfreechart.swing.pie».
3.2. Add jars to build path of your project
In your project create a folder «lib», and paste the JFreeChart jars into this folder.
You only need the following libraries. Please replace the version numbers with the version you are using.
Add these libraries to your classpath. See Eclipse Java IDE — Classpath for details.
3.3. Code
Create the following two classes.
I assume that the code is pretty much self-explaining. I tried to add lots of comments to make it easier to understand. For more complex examples have a look at the JFreeChart homepage.
Eclipse java swing как построить график
Автор этого материала — я — Пахолков Юрий. Я оказываю услуги по написанию программ на языках Java, C++, C# (а также консультирую по ним) и созданию сайтов. Работаю с сайтами на CMS OpenCart, WordPress, ModX и самописными. Кроме этого, работаю напрямую с JavaScript, PHP, CSS, HTML — то есть могу доработать ваш сайт или помочь с веб-программированием. Пишите сюда.
заметки, java, графики, задачи
Drawing a simple line graph in Java
In my program I want to draw a simple score line graph. I have a text file and on each line is an integer score, which I read in and want to pass as argument to my graph class. I’m having some trouble implementing the graph class and all the examples I’ve seen have their methods in the same class as their main, which I won’t have.
I want to be able to pass my array to the object and generate a graph, but when calling my paint method it is asking me for a Graphics g. This is what I have so far:
For now I have inserted a simple random number generator to fill up my array.
I have an existing frame and basically want to instantiate the Graph class and mount the panel onto my frame. I’m really sorry that this question seems so jumbled by the way, but I’ve had little sleep.
JFreeChart
In this article, we learn how to use JFreeChart. We show how to create various types of charts. The charts are displayed in a Swing application and saved to an image file. We use a Java servlet to create and render a chart in a web browser and retrieve data for a chart from a MySQL database.
Advertisements JFreeChart library
A chart is a drawing that shows information in a simple way, often using lines and curves to show amounts. is a popular Java library for creating charts. JFreeChart allows to create a wide variety of both interactive and non-interactive charts. We can create line charts, bar charts, area charts, scatter charts, pie charts, gantt charts and various specialized charts such as wind chart or bubble chart.
JFreeChart is extensively customizable; it allows to modify colours and paints of chart items, legends, styles of the lines or markers. It automatically draws the axis scales and legends. Charts have a built-in capability to zoom in with mouse. The existing charts can be easily updated through the listeners that the library has on its data collections. It supports multiple output formats including PNG, JPEG, PDF, and SVG.
JFreeChart was started by David Gilbert in 2000. Today, JFreeChart is the most widely used charting library among Java developers.
JFreeChart Maven dependency
For our projects we use this Maven dependency.
Advertisements JFreeChart histogram
A histogram is an accurate representation of the distribution of numerical data. It is an estimate of the probability distribution of a continuous variable.
In the example, we generate a histogram for a random distribution of values. The chart is generated into a PNG file and saved on the disk.
Histogram chart displays values in a HistogramDataset . The second argument of the addSeries method is the array of double values. The third is the number of bins, i.e. the number of rectangles drawn on the chart.
A histogram is created with the ChartFactory.createHistogram method.
We write the chart to a PNG image with ChartUtils.saveChartAsPNG .
JFreeChart line chart
A line chart is a basic type of chart which displays information as a series of data points connected by straight line segments. A line chart in JavaFX is created with the ChartFactory.createXYLineChart .
In the example, we create a line chart showing average salary per age.
XYSeries represents a sequence of zero or more data items in the form (x, y).
The series is added to the XYSeriesCollection , which is a collection of XYSeries objects that can be used as a dataset.
The ChartFactory.createXYLineChart creates a new line chart. The parameters of the method are: chart title, X axis label, Y axis label, data, plot orientation, and three flags indicating whether to show legend, tooltips, and URLs.
We get a reference to the plot in order to customize it.
Here, we set a stroke and a colour for the line of the chart. XYLineAndShapeRenderer is an object that connects data points with lines and/or draws shapes at each data point. The renderer is set with the setRenderer method.
The setBackgroundPaint sets the background colour of the plot area.
We show the grid lines and paint them in black colour.
We remove the border around the legend.
We create a chart title with a new font. Figure: Line chart
A line chart with two series
In the second example, we create a line chart having two data series.
The example draws a line chart with two data series.
We create the first series; it contains data for 2014.
A second data series is created; it contains data for 2016.
The series are added to the XYSeriesCollection with the addSeries method.
One line is painted in red colour and one in blue.
The grid lines are turned off. Figure: Line chart with two series Advertisements
Saving line chart to image
ChartUtils is a collection of utility methods for JFreeChart. It includes methods for converting charts to image formats and creating simple HTML image maps.
The example creates a line chart and saves it into a PNG file.
The ChartUtils.saveChartAsPNG saves a chart to the specified file in PNG format.
JFreeChart bubble chart
Bubble chart is a variation of a scatter chart with an additional dimension. Instead of data points, we use with bubbles. The first two dimensions are visualized as coordinates. The size of the bubbles represents the additional dimension.
A bubble chart is created with ChartFactory.createBubbleChart method in JFreeChart.
We have three products. With these products, we have their quantities, prices, and market shares. The quantities are placed on the x-axis and the prices on the y-axis. The market share values are z-values; they are represented by the bubbles.
The bubble chart uses the XYZDataset . The z-values (market share) is adjusted; we make the circles larger.
We create the chart with ChartFactory.createBubbleChart .
We adjust the values on the axes so that all bubbles are visible.
JFreeChart area chart
An area chart displays graphically quantitative data that change over time. An area chart is created with ChartFactory.createAreaChart method in JFreeChart.
The example shows an area chart showing world crude oil consumption by year.
A dataset is created with the DatasetUtils.createCategoryDataset method. A category dataset values associated with categories. In our examples, we have years associated with oil consumption.
We mave the chart transparent with the setForegroundAlpha method.
We adjust the endings of the chart. Figure: Area chart
JFreeChart bar chart
A bar chart presents grouped data with rectangular bars with lengths proportional to the values that they represent. The bars can be plotted vertically or horizontally.
The code example uses a bar chart to show the number of Olympic gold medals per country in London 2012.
We use a DefaultCategoryDataset to create a dataset.
A bar chart is created with the ChartFactory.createBarChart method. Figure: Bar chart
JFreeChart pie chart
A pie chart is a circular chart which is divided into slices to illustrate numerical proportion. A pie chart is created with the ChartFactory.createPieChart method in JFreeChart.
The example uses a pie chart to show the market share of web servers.
A DefaultPieDataset is used to create a dataset.
A new pie chart is created with the ChartFactory.createPieChart method.
Advertisements JFreeChart in a servlet
In the following example, we use a Java servlet to create a pie chart. The chart is rendered in a web browser.
The DoChart servlet creates a pie chart and sends it to the client.
The setContentType sets the content to a PNG image.
With the getOutputStream method we get an output stream. It is a tunnel to which we send the data.
The ChartUtils.writeChartAsPNG writes the binary data to the outputstrem. Figure: A pie chart in a browser
Advertisements Showing data from a MySQL database
JDBCCategoryDataset is a CategoryDataset implementation over a database JDBC result set. The dataset is populated via a call to executeQuery with the string SQL query.
We have this data in a MySQL database table.
We show the data with the mysql tool.
The example retrieves data from a MySQL table, creates a bar chart, and saves it into a PNG image.
JDBCCategoryDataset is created; it takes a database connection as a parameter.
The executeQuery populates the dataset by executing the supplied query against the existing database connection. The SQL query must return at least two columns. The first column is the category name and remaining columns are values.