Created
September 17, 2023 05:11
-
-
Save 0xJchen/1295e0d34a5bac1f01bdcc1282109429 to your computer and use it in GitHub Desktop.
JFreeChart test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package test; | |
import java.awt.*; | |
import java.awt.geom.Rectangle2D; | |
import java.awt.image.BufferedImage; | |
import java.io.BufferedOutputStream; | |
import java.io.File; | |
import java.io.FileOutputStream; | |
import java.io.IOException; | |
import java.io.OutputStream; | |
import org.jfree.chart.*; | |
import org.jfree.chart.plot.PlotOrientation; | |
import org.jfree.data.category.DefaultCategoryDataset; | |
import org.jfree.data.category.CategoryDataset; | |
public class ChartTest6 { | |
public static CategoryDataset datasetGenerator() { | |
DefaultCategoryDataset categoryData = new DefaultCategoryDataset(); | |
String[] carBrands = {"FIAT", "AUDI", "FORD"}; | |
String[] attributes = {"Velocity", "CustomerScore", "FuelEfficiency", "SecurityLevel"}; | |
double[][] values = { | |
{1.0, 3.0, 5.0, 5.0}, | |
{5.0, 6.0, 10.0, 4.0}, | |
{4.0, 2.0, 3.0, 6.0} | |
}; | |
for(int i = 0; i < carBrands.length; i++) { | |
for(int j = 0; j < attributes.length; j++) { | |
categoryData.addValue(values[i][j], carBrands[i], attributes[j]); | |
} | |
} | |
return categoryData; | |
} | |
public static JFreeChart generateBarChart(CategoryDataset dataSet) { | |
return ChartFactory.createBarChart("Automotive Attributes", "Attribute", "Value", | |
dataSet, PlotOrientation.VERTICAL, true, true, false); | |
} | |
public static JFreeChart generateLineChart(CategoryDataset dataSet) { | |
return ChartFactory.createLineChart("Automotive Attributes Line", "Attribute", "Value", | |
dataSet, PlotOrientation.VERTICAL, true, true, false); | |
} | |
public static void main(String[] args) throws IOException { | |
CategoryDataset dataSet = datasetGenerator(); | |
JFreeChart barChart = generateBarChart(dataSet); | |
JFreeChart lineChart = generateLineChart(dataSet); | |
saveChartAsPNG(barChart, "output5"); | |
saveChartAsPNG(lineChart, "output7"); | |
} | |
public static void saveChartAsPNG(JFreeChart chart, String fileName) throws IOException { | |
BufferedImage buffer = new BufferedImage(800, 600, BufferedImage.TYPE_INT_ARGB); | |
Graphics2D graphics = buffer.createGraphics(); | |
chart.draw(graphics, new Rectangle2D.Double(0, 0, 800, 600)); | |
graphics.dispose(); | |
try (OutputStream outStream = new BufferedOutputStream(new FileOutputStream(new File(fileName + ".png")))) { | |
ChartUtils.writeBufferedImageAsPNG(outStream, buffer); | |
} | |
System.out.println(fileName + ".png has been generated."); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment