如何像在 Matlab 中一样在 Java 中绘制绘图(相同语法)

2024-03-29

在 Matlab 中绘图非常简单明了。例如:

figure('Position_',[100,80,1000,600])         
plot(x,y1,'-.or','MarkerSize',0.2,'MarkerFaceColor','r','LineWidth',2)
xlabel('Matrix1')
ylabel('Matrix2')
grid on 
hold on
axis([-1,1,0,var1*1.2])
plot(x,y2,'-k','MarkerSize',0.5,'MarkerFaceColor','k','LineWidth',4)
title('My plot')
figuresdir = 'dir'; 
saveas(gcf,strcat(figuresdir, 'plotimage'), 'bmp');

然而,我发现用 Java 绘图更困难,我必须使用像 or 自由图表 http://www.jfree.org/jfreechart/。但是,我发现使用这些包合并绘图并将其打印到文件中很困难。

有没有一种简单的方法可以在 Java 中使用与 Matlab 相同的语法来绘制图形?


Matlab 是专门为使绘图等事情变得尽可能简单而设计的。其他语言根本不支持快速简单的绘图。

因此我决定编写一个基于 Matlab 风格的图表类自由图表 http://www.jfree.org/jfreechart/, 只为你:

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Stroke;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.annotations.XYTitleAnnotation;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.block.BlockBorder;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.title.LegendTitle;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.ui.RectangleAnchor;
import org.jfree.ui.RectangleEdge;


public class MatlabChart {

    Font font;
    JFreeChart chart;
    LegendTitle legend;
    ArrayList<Color> colors;
    ArrayList<Stroke> strokes;
    XYSeriesCollection dataset;

    public MatlabChart() {
        font = JFreeChart.DEFAULT_TITLE_FONT;
        colors = new ArrayList<Color>();
        strokes = new ArrayList<Stroke>();
        dataset = new XYSeriesCollection();
    }

    public void plot(double[] x, double[] y, String spec, float lineWidth, String title) {
        final XYSeries series = new XYSeries(title);
        for (int i = 0; i < x.length; i++)
            series.add(x[i],y[i]);
        dataset.addSeries(series);
        FindColor(spec,lineWidth);
    }

    public void RenderPlot() {
        // Create chart
        JFreeChart chart = null;
        if (dataset != null && dataset.getSeriesCount() > 0)
            chart = ChartFactory.createXYLineChart(null,null,null,dataset,PlotOrientation.VERTICAL,true, false, false);
        else
            System.out.println(" [!] First create a chart and add data to it. The plot is empty now!");
        // Add customization options to chart
        XYPlot plot = chart.getXYPlot();
        for (int i = 0; i < colors.size(); i++) {
            plot.getRenderer().setSeriesPaint(i, colors.get(i));
            plot.getRenderer().setSeriesStroke(i, strokes.get(i));
        }
        ((NumberAxis)plot.getDomainAxis()).setAutoRangeIncludesZero(false);
        ((NumberAxis)plot.getRangeAxis()).setAutoRangeIncludesZero(false);
        plot.setBackgroundPaint(Color.WHITE);
        legend = chart.getLegend();
        chart.removeLegend();
        this.chart = chart;
    }

    public void CheckExists() {
        if (chart == null) {
            throw new IllegalArgumentException("First plot something in the chart before you modify it.");
        }
    }

    public void font(String name, int fontSize) {
        CheckExists();
        font = new Font(name, Font.PLAIN, fontSize);
        chart.getTitle().setFont(font);
        chart.getXYPlot().getDomainAxis().setLabelFont(font);
        chart.getXYPlot().getDomainAxis().setTickLabelFont(font);
        chart.getXYPlot().getRangeAxis().setLabelFont(font);
        chart.getXYPlot().getRangeAxis().setTickLabelFont(font);
        legend.setItemFont(font);
    }

    public void title(String title) {
        CheckExists();
        chart.setTitle(title);
    }

    public void xlim(double l, double u) {
        CheckExists();
        chart.getXYPlot().getDomainAxis().setRange(l, u);
    }

    public void ylim(double l, double u) {
        CheckExists();
        chart.getXYPlot().getRangeAxis().setRange(l, u);
    }

    public void xlabel(String label) {
        CheckExists();
        chart.getXYPlot().getDomainAxis().setLabel(label);
    }

    public void ylabel(String label) {
        CheckExists();
        chart.getXYPlot().getRangeAxis().setLabel(label);
    }

    public void legend(String position) {
        CheckExists();
        legend.setItemFont(font);
        legend.setBackgroundPaint(Color.WHITE);
        legend.setFrame(new BlockBorder(Color.BLACK));
        if (position.toLowerCase().equals("northoutside")) {
            legend.setPosition(RectangleEdge.TOP);
            chart.addLegend(legend);
        } else if (position.toLowerCase().equals("eastoutside")) {
            legend.setPosition(RectangleEdge.RIGHT);
            chart.addLegend(legend);
        } else if (position.toLowerCase().equals("southoutside")) {
            legend.setPosition(RectangleEdge.BOTTOM);
            chart.addLegend(legend);
        } else if (position.toLowerCase().equals("westoutside")) {
            legend.setPosition(RectangleEdge.LEFT);
            chart.addLegend(legend);
        } else if (position.toLowerCase().equals("north")) {
            legend.setPosition(RectangleEdge.TOP);
            XYTitleAnnotation ta = new XYTitleAnnotation(0.50,0.98,legend,RectangleAnchor.TOP);
            chart.getXYPlot().addAnnotation(ta);
        } else if (position.toLowerCase().equals("northeast")) {
            legend.setPosition(RectangleEdge.TOP);
            XYTitleAnnotation ta = new XYTitleAnnotation(0.98,0.98,legend,RectangleAnchor.TOP_RIGHT);
            chart.getXYPlot().addAnnotation(ta);
        } else if (position.toLowerCase().equals("east")) {
            legend.setPosition(RectangleEdge.RIGHT);
            XYTitleAnnotation ta = new XYTitleAnnotation(0.98,0.50,legend,RectangleAnchor.RIGHT);
            chart.getXYPlot().addAnnotation(ta);
        } else if (position.toLowerCase().equals("southeast")) {
            legend.setPosition(RectangleEdge.BOTTOM);
            XYTitleAnnotation ta = new XYTitleAnnotation(0.98,0.02,legend,RectangleAnchor.BOTTOM_RIGHT);
            chart.getXYPlot().addAnnotation(ta);
        } else if (position.toLowerCase().equals("south")) {
            legend.setPosition(RectangleEdge.BOTTOM);
            XYTitleAnnotation ta = new XYTitleAnnotation(0.50,0.02,legend,RectangleAnchor.BOTTOM);
            chart.getXYPlot().addAnnotation(ta);
        } else if (position.toLowerCase().equals("southwest")) {
            legend.setPosition(RectangleEdge.BOTTOM);
            XYTitleAnnotation ta = new XYTitleAnnotation(0.02,0.02,legend,RectangleAnchor.BOTTOM_LEFT);
            chart.getXYPlot().addAnnotation(ta);
        } else if (position.toLowerCase().equals("west")) {
            legend.setPosition(RectangleEdge.LEFT);
            XYTitleAnnotation ta = new XYTitleAnnotation(0.02,0.50,legend,RectangleAnchor.LEFT);
            chart.getXYPlot().addAnnotation(ta);
        } else if (position.toLowerCase().equals("northwest")) {
            legend.setPosition(RectangleEdge.TOP);
            XYTitleAnnotation ta = new XYTitleAnnotation(0.02,0.98,legend,RectangleAnchor.TOP_LEFT);
            chart.getXYPlot().addAnnotation(ta);
        }
    }

    public void grid(String xAxis, String yAxis) {
        CheckExists();
        if (xAxis.equalsIgnoreCase("on")){
            chart.getXYPlot().setDomainGridlinesVisible(true);
            chart.getXYPlot().setDomainMinorGridlinesVisible(true);
            chart.getXYPlot().setDomainGridlinePaint(Color.GRAY);
        } else {
            chart.getXYPlot().setDomainGridlinesVisible(false);
            chart.getXYPlot().setDomainMinorGridlinesVisible(false);
        }
        if (yAxis.equalsIgnoreCase("on")){
            chart.getXYPlot().setRangeGridlinesVisible(true);
            chart.getXYPlot().setRangeMinorGridlinesVisible(true);
            chart.getXYPlot().setRangeGridlinePaint(Color.GRAY);
        } else {
            chart.getXYPlot().setRangeGridlinesVisible(false);
            chart.getXYPlot().setRangeMinorGridlinesVisible(false);
        }
    }

    public void saveas(String fileName, int width, int height) {
        CheckExists();
        File file = new File(fileName); 
        try {
            ChartUtilities.saveChartAsJPEG(file,this.chart,width,height);
        } catch (IOException e) {
            e.printStackTrace();
        }  
    }

    public void FindColor(String spec, float lineWidth) {
        float dash[] = {5.0f};
        float dot[] = {lineWidth};
        Color color = Color.RED;                    // Default color is red
        Stroke stroke = new BasicStroke(lineWidth); // Default stroke is line   
        if (spec.contains("-"))
            stroke = new BasicStroke(lineWidth);
        else if (spec.contains(":"))
            stroke = new BasicStroke(lineWidth, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, dash, 0.0f);
        else if (spec.contains("."))
            stroke = new BasicStroke(lineWidth, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 2.0f, dot, 0.0f);
        if (spec.contains("y"))
            color = Color.YELLOW;
        else if (spec.contains("m"))
            color = Color.MAGENTA;
        else if (spec.contains("c"))
            color = Color.CYAN;
        else if (spec.contains("r"))
            color = Color.RED;
        else if (spec.contains("g"))
            color = Color.GREEN;
        else if (spec.contains("b"))
            color = Color.BLUE;
        else if (spec.contains("k"))
            color = Color.BLACK;
        colors.add(color);
        strokes.add(stroke);
    }
}

这样,您就可以使用与 Matlab 非常接近的语法在 Java 中进行绘图:

public class Demo {

    public static void main(String[] args) {

        // Create some sample data
        double[] x = new double[100]; x[0] = 1;
        double[] y1 = new double[100]; y1[0] = 200;
        double[] y2 = new double[100]; y2[0] = 300;
        for(int i = 1; i < x.length; i++){
            x[i] = i+1; 
            y1[i] = y1[i-1] + Math.random()*10 - 4;
            y2[i] = y2[i-1] + Math.random()*10 - 6;
        }

        // JAVA:                             // MATLAB:
        MatlabChart fig = new MatlabChart(); // figure('Position',[100 100 640 480]);
        fig.plot(x, y1, "-r", 2.0f, "AAPL"); // plot(x,y1,'-r','LineWidth',2);
        fig.plot(x, y2, ":k", 3.0f, "BAC");  // plot(x,y2,':k','LineWidth',3);
        fig.RenderPlot();                    // First render plot before modifying
        fig.title("Stock 1 vs. Stock 2");    // title('Stock 1 vs. Stock 2');
        fig.xlim(10, 100);                   // xlim([10 100]);
        fig.ylim(200, 300);                  // ylim([200 300]);
        fig.xlabel("Days");                  // xlabel('Days');
        fig.ylabel("Price");                 // ylabel('Price');
        fig.grid("on","on");                 // grid on;
        fig.legend("northeast");             // legend('AAPL','BAC','Location','northeast')
        fig.font("Helvetica",15);            // .. 'FontName','Helvetica','FontSize',15
        fig.saveas("MyPlot.jpeg",640,480);   // saveas(gcf,'MyPlot','jpeg');
    }
}

现在我们可以将最终的 JFreeChart 图形与我们从这段代码中获得的相同 Matlab 图形进行比较:

figure('Position',[100 100 640 480]); hold all;
plot(x,y1,'-r','LineWidth',2);
plot(x,y2,':k','LineWidth',3);
title('Stock 1 vs. Stock 2');
xlim([10 100]);
ylim([200 300]);
xlabel('Days');
ylabel('Price');
grid on;
legend('AAPL','BAC','Location','northeast');
saveas(gcf,'MyPlot','jpeg');

结果Java(使用 MatlabChart() 类):

结果Matlab:

The MatlabChart()我编写的类支持 Matlab 中的一些基本绘图语法。您可以指示线条样式(:,-,.),更改线条颜色(y,m,c,r,g,b,w,k),改变LineWidth并更改图例的位置(northoutside,eastoutside,soutoutside, westoutside,north,east,south,west,northeast,southeast,southwest,northwest)。您还可以将gridx 轴和 y 轴独立打开。例如:grid("off","on");转动x轴网格off并转动y轴网格on.

对于那些习惯在 Matlab 中绘图的人来说,这应该会让 Java 绘图变得更加容易:)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何像在 Matlab 中一样在 Java 中绘制绘图(相同语法) 的相关文章

随机推荐

  • 如何在 gnuplot 中设置网格间距

    我的 yaxis 从 0 到 100 我想要每 10 个单位后有一条网格线 我怎样才能做到这一点 即如何在每10个单位之后绘制网格线 看看 帮助网格 你可能想做类似的事情 set yrange 0 100 set xrange 0 10 s
  • 为什么 DWORD 值通常以十六进制表示?

    我试图理解为什么 DWORD 值经常在 MSDN 上以十六进制描述 我分析这个的原因是因为我试图从根本上理解为什么所有这些不同的数字数据类型存在 一位当地导师向我暗示 DWORD 和其他 Microsoft 类型的创建与处理器的发展有关 这
  • 如何接受像“2.0”这样的整数,但例如“2.1”作为浮点数? Python

    我试图让用户在输入字母或非整数时收到错误消息 并且当输入整数时 程序将继续显示该整数的平方和立方 我的老师不希望代码出现任何 中断 或任何 ValueErrors print Squaring and cubing integer prog
  • 将 xgboost.Booster 类转换为 XGBRegressor 或从 xgboost.Booster 加载 XGBRegressor

    我从 Sagemaker 获得了一个模型 其类型为
  • 使用标签和优先级记录到 Crashlytics,而无需发送到 logcat

    根据以下说明 有两种方式登录 Crashlytics文档 https docs fabric io android crashlytics enhanced reports html custom logging Crashlytics l
  • 如何捕获通过读/写文件引发的所有异常?

    在Java中 有没有办法获取 捕获 所有exceptions而不是单独捕获异常 如果需要 您可以向方法中添加 throws 子句 那么你不必立即捕获检查的方法 这样 您就可以抓住exceptions稍后 也许与其他时间同时 exceptio
  • 将 SWIG 与构建系统结合使用[关闭]

    很难说出这里问的是什么 这个问题是含糊的 模糊的 不完整的 过于宽泛的或修辞性的 无法以目前的形式得到合理的回答 如需帮助澄清此问题以便重新打开 访问帮助中心 help reopen questions 有人有使用 SWIG 界面生成器 的
  • Codeigniter 数据库插入失败

    目前在我的控制器中 当添加新数据时 我会验证输入 如果存在任何问题 它会让用户知道 否则它将数据传递到模型以插入到数据库中 现在我如何检查插入语句在模型中是否正常工作 并让用户知道是否没有 像下面这样的插入语句是否返回 true 或 fal
  • HTML5 视频自动播放且声音未静音

    我需要在我的网站上实现本地自动播放视频 不过 我知道 当视频没有 静音 属性时 较新的浏览器 即 Chrome Mozilla 和 Safari 会阻止自动播放 所以 有没有办法通过 HTML 或 Javascript 中的任何技巧在 HT
  • 成员函数定义

    正确的做法是什么 定义成员 类 函数inside班上 定义成员 类 函数outside班上 Thanks 假设您正在谈论这三种可能性 头文件中的类定义中定义的方法 方法在头文件中定义在类定义之外 方法定义在实现文件中的类定义之外 那么项目和
  • node_modules/@types/react-dom/... 处出现错误。后续变量声明必须具有相同的类型。变量“a”

    我已经安装了 types react dom 以及 typescript types react 和 types meteor 但是当我尝试从命令行运行类型检查器时 出现以下错误 您可以在此处重现错误并查看我的所有配置 https gith
  • 强制嵌入推文为 100% 宽度

    我试图通过将宽度设置为 100 来强制嵌入的推文做出响应式行为 我尝试按如下方式调整内联宽度 blockquote class twitter tweet width 100 blockquote 我还尝试对 twitter tweet 类
  • C 字符串初始值设定项不包含终止符?

    我对以下 C 代码片段有点困惑 printf Peter string is d bytes n sizeof Peter Peter string is 6 bytes 这告诉我 当 C 编译双引号中的字符串时 它会自动为空终止符添加一个
  • 使用Gson时出现奇怪的“nameValuePairs”键

    我正在尝试重建一个Object从它的字段 我将字段作为 JSONObject 获取 如下所示 JSONObject jObj new JSONObject JSONObject jObj1 new JSONObject JSONObject
  • Apache CXF 客户端代理设置

    我正在尝试使用以下教程开发肥皂服务的消费者http cxf apache org docs developing a consumer html http cxf apache org docs developing a consumer
  • GNU Mailman 的简单/轻量级替代品?

    我正在寻找一个非常简单的邮件列表 unix 友好 稳健性 细粒度可配置性 企业就绪性 无论这意味着什么 都不是要求 我只需要为几个朋友建立一个小型邮件列表 我不想自己破解一些东西 而是想知道是否有人知道已经有类似目标的东西 我现在应该注意的
  • 如何使用 log4j2 Commons 日志桥

    我想将 log4j2 Commons Logging Bridge 与 commons 1 2 一起使用 我尝试使用如下内容 import org apache logging log4j jcl LogFactoryImpl public
  • 在 ASP.net MVC 中通过 jQuery 在客户端本地化验证消息

    我使用 jquery 进行客户端验证以及数据注释 一切工作正常 但我想在数字文本框中输入非数字值时本地化消息 对于服务器端验证 可以通过将 DefaultModelBinder ResourceClassKey 设置为资源类名称并为 Pro
  • 如何获取手机的位置

    我正在编写一个管理非常大的表的脚本 当用户单击表格单元格时 我想知道他们单击了哪个单元格 例如 Click 应该给我一个 1 1 的单元格引用 无论如何我都可以用 javascript 来做到这一点 它运行的页面将 jquery 用于其他目
  • 如何像在 Matlab 中一样在 Java 中绘制绘图(相同语法)

    在 Matlab 中绘图非常简单明了 例如 figure Position 100 80 1000 600 plot x y1 or MarkerSize 0 2 MarkerFaceColor r LineWidth 2 xlabel M