×

Java Plot

Java Plot is a phrase in Java that is mostly used for plotting coordinates on a cartesian plane. Plotting graphs in Java is accomplished through the use of various core Java concepts. We plot with swing, awt, and awt.geom.

  • In program, we use the Swing package to implement Jlabel, JButtons, and JPanel.
  • To create a graphical user interface for the project's front-end, we use AWT (Abstract Window Toolkit).
  • To conduct two-dimensional geometry operations, the awt.geom package is utilised.

To plot a point on a graph, we employ numerous graphics techniques such as draw (), setPaint (), and Fill (), among others. Let's have a look at a graph to see how we can plot coordinates in Java.

PlotJex.java:

import java.awt.*;  
import javax.swing.*;  
import java.awt.geom.*;  
  
public class PlotJex extends JPanel{  
   
    int[] crd = {75, 30, 50, 90};  
    int mrg = 78;  
      
    protected void paintComponent(Graphics grcs){  
        
        super.paintComponent(grcs);  
        Graphics2D gph = (Graphics2D)grcs;  
          
        //Sets the value of a single preference for the rendering algorithms.  
        gph.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);  
          
        // wdt-width and hgt-height  
        int wdt = getWidth();  
        int hgt = getHeight();  
        gph.draw(new Line2D.Double(mrg, mrg, mrg, hgt-mrg));  
        gph.draw(new Line2D.Double(mrg, hgt-mrg, wdt-mrg, hgt-mrg));  
        double x = (double)(wdt-2*mrg)/(crd.length-1);  
        double scale = (double)(hgt-2*mrg)/getMax();  
        // color the points  
        gph.setPaint(Color.GREEN);  
        // points on the graph  
        for(int i=0; i<crd.length; i++){  
            double xp1 = mrg+i*x;  
            double yp1 = hgt-mrg-scale*crd[i];  
            gph.fill(new Ellipse2D.Double(xp1-2, yp1-2, 4, 4));  
        }  
    }  
    // getMax() to find max value  
    private int getMax(){  
        int mx = -Integer.MAX_VALUE;  
        for(int i=0; i<crd.length; i++){  
            if(crd[i]>mx)  
                mx = crd[i];               
        }  
        return mx;  
    }         
    public static void main(String args[]){  
        // instance for JFrame   
        JFrame frm = new JFrame();  
        // size,location and layout  
        frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
        frm.add(new PlotJex());  
        frm.setSize(350, 340);  
        frm.setLocation(250, 210);  
        frm.setVisible(true);  
    }  
}  

Output :

Java Plot

PlotExample is the class created in the preceding code for plotting the graph, and chord is an array of values that are treated as coordinates to be plotted on the graph. In addition, we enhance the JPanel class to represent the graph.

Note: The Panel's layout is Flow-Layout by default, but we may change it to any other layout we like, such as grid layout, card layout, box layout, and border layout, among others.

To draw the graph on JPanel, we use super.paintComponent(g). We use the Super keyword in our code to invoke the parent class method or function Object () { [native code] }. In our scenario, the Super function invokes the JPanel class's paintComponent (g) method.

For control over geometry, we use the Graphic 2D class (a fundamental class for two-dimensional shapes that extends the Graphics class).

We employ RenderingHints, which are basic suggestions for Java 2D on how it should render. Simply put, rendering refers to how something is done.

The setRenderingHints () function is used to set new hints and change old ones.

Antialiasing is used to smooth jagged edges when the resolution is poor.

We need four coordinates to create lines representing the x and y axes: x1, y1, x2, and y2. In our code, we utilise the g1.draw () function to create lines.

To change the colour of the points on the graph, we utilise the setpaint () function.

We utilise the for loop in our code, and coordinates are used within that loop.

length () returns the coordinates array's length.

We utilise the getWidth () and getHeight () methods of the component to get the component's height and width.

Instead of the cartesian plane, we plot the points with regard to the size of the component using the xp1 and yp1 variables.


Related Topics

Java Binary Operators

In this article, we are going to discuss about the binary operators in Java and their operations. Also, an example program will be discussed along with the operations. These are...

6 minutes read.

Session Tracking in Java

When a series of requests from the same User (i.e., requests coming from the same browser) occurs over an extended period of time, servlets employ a mechanism known as session...

3 minutes read.

Java Math expm1() Method

The expm1() method of Math class returns ex-1 where e represents Euler’s number. Syntax: public static double expm1(double x) Parameters: The parameter ‘x’ represents the exponent to raise e in the calculation of ex-1. Return...

2 minutes read.

Stack in Java

Java provides a number of collection frameworks to store the collection of objects. Among the collection of data structures " Stack " is one of them. Stack is one of...

5 minutes read.

Constructor Overloading in Java

In Java, constructors can be overloaded just like methods. The idea of having multiple constructors with various parameter sets so that each function Object()  can carry out a particular task...

3 minutes read.

Java array list remove time complexity

Java: We know that java is one of the programming languages. The main feature of java which is not in C or object oriented programming language is platform independence. Not only the...

7 minutes read.

Heart Pattern in Java

Heart Pattern is yet another intricate pattern program, however, due to its complexity, interviewers hardly ever inquire about it. Method for Printing the Heart Number Pattern Put the value of the total row...

2 minutes read.

Java Network Programming (Socket Programming in Java)

JAVA NETWORK Network programming is used to execute programs across multiple machines that are connected by a network. The java.net package contains a collection of classes and interfaces that provide this...

3 minutes read.

Union in Java

Sets.union() method in Java returns an immutable representation of both the union of two sets. Every element that is present in either backup set is included in the set that...

2 minutes read.

Bully Algorithm code in Java

Election algorithms include the bully algorithm, mainly used to select a coordinate. To find a coordinator in a distributed system that can carry out the tasks required by other processes,...

4 minutes read.

Topological Sort In Java

Topological Sort in Java Topological sort is mainly used in the linear ordering of vertices in a Directed Acyclic Graph (DAG). Topological sort in Java illustrates how to do the linear ordering of...

1 minute read.

How to Convert int to double in Java

How to Convert int to double in Java When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to...

2 minutes read.

Class definition in Java

The class definition in Java Java is an object-oriented programming language. We essentially know that programming languages based on object-oriented paradigms have classes and objects in their concepts as main, which...

6 minutes read.

JDBC vs ODBC

Difference Between JDBC and ODBC ODBC: ODBC (Open Database Connectivity) is the accepted method for accessing databases among organisations and programmers. A database is linked to other programmes, such as word processors, spreadsheets,...

4 minutes read.

How to Convert String to boolean in Java

How to Convert String to boolean in Java There are two methods to convert String to boolean: Using parseBoolean(string) method Using valueOf(string) method If the string contains "True," "true," or "TRUE,"...

3 minutes read.

Java Math abs() Method

The abs() method of Math class returns the absolute value of the argument where the argument can be int, double, float, long. Syntax public static int abs(int a) public static float abs(float a) public...

2 minutes read.

How to Split String by Comma in Java

strsplit() technique permits you to break a string given the explicit Java string delimiter. The Java string split property is frequently a space or a comma(,) that you want to...

7 minutes read.

Creating API Document Javadoc tool

The JavaDoc utility is a document generator tool written in Java that generates standard documentation in HTML format. It parses declarations and documentation in a source file collection that describes...

3 minutes read.

Difference between JIT and JVM in Java

In this tutorial, we will discuss the difference between JIT (Just In Time Compiler) and JVM (Java Virtual Machine) in Java. Before we move to the differences, let's understand what...

4 minutes read.

Java Exception Propagation

Java Exception Propagation When an exception is being thrown from the peak of the stack and not getting caught, it runs down the stack to the previous method, which is sitting...

3 minutes read.