JFreeChart圖表製作例項

kuLong_x發表於2020-12-16

JFreeChart圖表製作之折線圖/柱形圖


以共享單車為例
··折線圖反映了平均每10分鐘騎行的單車數量,以工大和浙工大在某時間段的資料為樣本,從一天的0點到一天的24點
··柱狀圖反映了學生平均騎行單車的時間,以工大和浙工大在某時間段的資料為樣本,一個柱子表示一次騎行的時間,大於100分鐘算100分鐘。

折線圖

package 課設;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.chart.title.TextTitle;
import org.jfree.chart.title.Title;
import org.jfree.chart.util.DefaultShadowGenerator;
import org.jfree.chart.util.ShadowGenerator;
import org.jfree.data.general.SeriesException;
import org.jfree.data.time.Second;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.XYDataset;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;

public class TimlyUsedModel extends ApplicationFrame {
	private static ReadCsv ZJUTcsv = new ReadCsv("zjutSharedbike-sample.csv");
	private static ReadCsv ZJUcsv = new ReadCsv("zjuSharedbike-sample.csv");
	private static List<int[]> ZjutTimlyUsedList = ZJUTcsv.CreateTimlyUsedList2();
	private static List<int[]> ZjuTimlyUsedList = ZJUcsv.CreateTimlyUsedList2();

	public TimlyUsedModel(final String title) throws ParseException {
		super(title);
		final XYDataset dataset = createDataset();
		final JFreeChart chart = createChart(dataset);
		final ChartPanel chartPanel = new ChartPanel(chart);
		chartPanel.setPreferredSize(new java.awt.Dimension(1200, 500));
		chartPanel.setMouseZoomable(true, false);
		setContentPane(chartPanel);
	}

	private XYDataset createDataset() throws ParseException {
		final TimeSeries seriesZJUT = new TimeSeries("ZJUT");
		final TimeSeries seriesZJU = new TimeSeries("ZJU");
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		double value = 100.0;
		int Errornum1 = 0;
		int Errornum2 = 0;
		for (int i = 0; i < ZjutTimlyUsedList.size(); i++) {
			try {
				String timeStr = "2018-1-1 " + ZjutTimlyUsedList.get(i)[0] + ":" + ZjutTimlyUsedList.get(i)[1] + ":0";
				Date time = df.parse(timeStr);
				Second current = new Second(time);
				value = ZjutTimlyUsedList.get(i)[2] / 79.0;
				seriesZJUT.add(current, value);
			} catch (SeriesException e) {
				System.err.println("Error adding to series1 "+ ++Errornum1);
			}
		}

		for (int i = 0; i < ZjuTimlyUsedList.size(); i++) {
			try {
				String timeStr = "2018-1-1 " + ZjuTimlyUsedList.get(i)[0] + ":" + ZjuTimlyUsedList.get(i)[1] + ":0";
				Date time = df.parse(timeStr);
				Second current = new Second(time);
				value = ZjuTimlyUsedList.get(i)[2] / 12.0;
				seriesZJU.add(current, value);
			} catch (SeriesException e) {
				System.err.println("Error adding to series2 "+ ++Errornum2);
			}
		}
		TimeSeriesCollection collection = new TimeSeriesCollection();
		collection.addSeries(seriesZJUT);
		collection.addSeries(seriesZJU);
		return (XYDataset) collection;
	}

	private JFreeChart createChart(final XYDataset dataset) {
		JFreeChart jFreeChart = ChartFactory.createTimeSeriesChart(
				"Statistics of bike-sharing trips in a day between The ZJUT and ZJU (10 minutes)", "Time", "Times/10Minutes",
				dataset, true, true, false);
		jFreeChart.addSubtitle((Title) new TextTitle("Java Course Design"));
		XYPlot xYPlot = (XYPlot) jFreeChart.getPlot();
		xYPlot.setShadowGenerator((ShadowGenerator) new DefaultShadowGenerator());
		DateAxis dateAxis = (DateAxis) xYPlot.getDomainAxis();
		dateAxis.setLowerMargin(0); // 下方Date這個小標題
		dateAxis.setTickLabelFont(new Font("宋體", Font.BOLD, 15));
		xYPlot.setDomainCrosshairVisible(true);// 設定縱向的定位線
		xYPlot.setRangeCrosshairVisible(true);// 設定橫向的定位線
		XYItemRenderer xYItemRenderer = xYPlot.getRenderer();// 折線例項
		if (xYItemRenderer instanceof XYLineAndShapeRenderer) {
			XYLineAndShapeRenderer xYLineAndShapeRenderer = (XYLineAndShapeRenderer) xYItemRenderer;
			xYLineAndShapeRenderer.setBaseStroke(new BasicStroke(3.0F));
			xYLineAndShapeRenderer.setSeriesPaint(0, new Color(1742401));// 重新設定曲線顏色為深綠
		}
		return jFreeChart;
	}

	public static void main(final String[] args) throws ParseException {
		final String title = "Time Series Management";
		final TimlyUsedModel demo = new TimlyUsedModel(title);
		demo.pack();
		RefineryUtilities.positionFrameRandomly(demo);
		demo.setVisible(true);
	}
}

在這裡插入圖片描述

柱形圖

package 課設;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.RenderingHints;
import java.awt.Window;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Map;
import java.util.Map.Entry;

import javax.swing.JPanel;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.LegendItemSource;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.block.BlockBorder;
import org.jfree.chart.block.BlockFrame;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.StandardXYItemLabelGenerator;
import org.jfree.chart.labels.StandardXYToolTipGenerator;
import org.jfree.chart.labels.XYItemLabelGenerator;
import org.jfree.chart.labels.XYToolTipGenerator;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.StackedXYBarRenderer;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.title.LegendTitle;
import org.jfree.chart.title.TextTitle;
import org.jfree.chart.title.Title;
import org.jfree.data.xy.DefaultTableXYDataset;
import org.jfree.data.xy.TableXYDataset;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RectangleEdge;
import org.jfree.ui.RefineryUtilities;
import org.jfree.ui.TextAnchor;

public class UsingTimeCompareStackBar extends ApplicationFrame {
	private static ReadCsv ZJUTcsv = new ReadCsv("zjutSharedbike-sample.csv");
	private static ReadCsv ZJUcsv = new ReadCsv("zjuSharedbike-sample.csv");
	private static ReadCsv Socialcsv = new ReadCsv("SocaiSharedBike-sample.csv");
	private static Map<Integer, Integer> ZjutUsingTimeMap = ZJUTcsv.createUsingTimeMap();
	private static Map<Integer, Integer> ZjuUsingTimeMap = ZJUcsv.createUsingTimeMap();
	private static Map<Integer, Integer> SocialUsingTimeMap = Socialcsv.createUsingTimeMap();
	public UsingTimeCompareStackBar(String paramString) {
		super(paramString);
		JPanel jPanel = createDemoPanel();
		jPanel.setPreferredSize(new Dimension(1300, 500));
		setContentPane(jPanel);
	}

	private static TableXYDataset createDataset() {
		DefaultTableXYDataset Dataset = new DefaultTableXYDataset();
		XYSeries xYZJUT = new XYSeries("ZJUT", true, false);
		XYSeries xYZJU = new XYSeries("ZJU", true, false);
		XYSeries xYSocial= new XYSeries("Social", true, false);
		for (Entry<Integer, Integer> entry : ZjutUsingTimeMap.entrySet()) {
			xYZJUT.add(entry.getKey(), entry.getValue());
		}
		for (Entry<Integer, Integer> entry : ZjuUsingTimeMap.entrySet()) {
			xYZJU.add(entry.getKey(), entry.getValue());
		}
		for (Entry<Integer, Integer> entry : SocialUsingTimeMap.entrySet()) {
			xYSocial.add(entry.getKey(), entry.getValue());
		}
		Dataset.addSeries(xYZJUT);
		Dataset.addSeries(xYZJU);
//		Dataset.addSeries(xYSocial);
		return (TableXYDataset) Dataset;
	}

	private static JFreeChart createChart(TableXYDataset paramTableXYDataset) {
		NumberAxis dateAxis = new NumberAxis("Traveling Using Time");
		dateAxis.setLowerMargin(0.01D);
		dateAxis.setUpperMargin(0.01D);
		NumberAxis numberAxis = new NumberAxis("Count");
		numberAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
//		numberAxis.setUpperMargin(0.1D);
		StackedXYBarRenderer stackedXYBarRenderer = new StackedXYBarRenderer(0.15D);
		stackedXYBarRenderer.setDrawBarOutline(false);
		stackedXYBarRenderer.setBaseItemLabelsVisible(false);
		stackedXYBarRenderer.setBaseItemLabelGenerator((XYItemLabelGenerator) new StandardXYItemLabelGenerator());
		stackedXYBarRenderer.setBasePositiveItemLabelPosition(
				new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BOTTOM_CENTER));
		stackedXYBarRenderer
				.setBaseToolTipGenerator((XYToolTipGenerator) new StandardXYToolTipGenerator("{0} : {1} = {2}",
						new SimpleDateFormat("yyyy"), new DecimalFormat("0")));
		XYPlot xYPlot = new XYPlot((XYDataset) paramTableXYDataset, (ValueAxis) dateAxis, (ValueAxis) numberAxis,
				(XYItemRenderer) stackedXYBarRenderer);
		JFreeChart jFreeChart = new JFreeChart("Comparison of average time of using shared bikes between ZJUT and ZJU",
				(Plot) xYPlot);
		jFreeChart.removeLegend();
//    jFreeChart.addSubtitle((Title)new TextTitle("PGA Tour, 1983 to 2003"));
		TextTitle textTitle = new TextTitle("JAVA COURSE DESIGN", new Font("Dialog", 0, 8));
		jFreeChart.addSubtitle((Title) textTitle);
		jFreeChart.setTextAntiAlias(RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT);
		LegendTitle legendTitle = new LegendTitle((LegendItemSource) xYPlot);
		legendTitle.setBackgroundPaint(Color.white);
		legendTitle.setFrame((BlockFrame) new BlockBorder());
		legendTitle.setPosition(RectangleEdge.BOTTOM);
		jFreeChart.addSubtitle((Title) legendTitle);
		ChartUtilities.applyCurrentTheme(jFreeChart);
		return jFreeChart;
	}

	public static JPanel createDemoPanel() {
		JFreeChart jFreeChart = createChart(createDataset());
		return (JPanel) new ChartPanel(jFreeChart);
	}

	public static void main(String[] paramArrayOfString) {
		UsingTimeCompareStackBar stackedXYBarChartDemo2 = new UsingTimeCompareStackBar(
				"Comparison of average time of using shared bikes between ZJUT and ZJU");
		stackedXYBarChartDemo2.pack();
		RefineryUtilities.centerFrameOnScreen((Window) stackedXYBarChartDemo2);
		stackedXYBarChartDemo2.setVisible(true);
	}
}

在這裡插入圖片描述

有需要具體解釋的或者知識點詳解可以評論私我,我可以補充一些地方

相關文章