Jfreechart之 使用Java/scala 绘图

一、pom.xml

    <!-- https://mvnrepository.com/artifact/org.jfree/jfreechart -->
    <dependency>
      <groupId>org.jfree</groupId>
      <artifactId>jfreechart</artifactId>
      <version>1.0.19</version>
    </dependency>

二、LineGraph.scala

package com.njbdqn.Kmeans

import java.awt.Font

import org.jfree.chart.{ChartFactory, ChartPanel}
import org.jfree.chart.plot.PlotOrientation
import org.jfree.data.category.DefaultCategoryDataset
import org.jfree.ui.ApplicationFrame

import scala.collection.mutable.ListBuffer

/**
 * 绘图
 * @param appName
 */
class LineGraph(appName: String) extends ApplicationFrame(appName) {
  def this(appName:String,title:String,list:ListBuffer[Double]) {
    this(appName)
    // 1. 折现图参数设置
    val lineChart = ChartFactory.createLineChart(title,
      "X轴代表什么", "Y轴代表什么", createDataset(list),
      PlotOrientation.VERTICAL, true, true, false)
    // 2. 设置窗口字体
    val font = new Font("宋体", Font.BOLD, 20)
    lineChart.getTitle.setFont(font)//设置标题
    lineChart.getLegend.setItemFont(font)//设置标签字体
    lineChart.getCategoryPlot.getDomainAxis.setLabelFont(font)//设置x轴字体
    lineChart.getCategoryPlot.getRangeAxis.setLabelFont(font)//设置y轴字体
    // 3. 折线图面板
    val chartPanel = new ChartPanel(lineChart)
    chartPanel.setPreferredSize(new java.awt.Dimension(1600, 1200))
    setContentPane(chartPanel)
  }

// 生成数据
  def createDataset(list: ListBuffer[Double]): DefaultCategoryDataset = {
    val dataset = new DefaultCategoryDataset();
    var point=2;
    for (dst <- list){
      // addValue(double Y轴数据, Comparable 折线代表的含义, Comparable X轴数据)
      dataset.addValue(dst,"distance",point)
      point+=1
    }
    dataset;
  }
}

三、Test类测试使用

package com.njbdqn.Kmeans

import org.jfree.ui.RefineryUtilities

import scala.collection.mutable.ListBuffer

object GraphTest {
  def main(args: Array[String]): Unit = {
    val disList:ListBuffer[Double]=ListBuffer[Double]()
    // 调用
    val lg = new LineGraph("app","我的窗口",disList)
    lg.pack()
    RefineryUtilities.centerFrameOnScreen(lg)
    lg.setVisible(true)
  }
}

 

posted @ 2020-10-16 08:49  PEAR2020  阅读(233)  评论(0编辑  收藏  举报