DScience:2D representation of data

From HandWiki
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.
Member


30% complete
   


A Plot is a technique for graphical representation of data. Two-dimensional (2D) plots are graph showing the relationship between two variables, X and Y.

Interactive 2D canvases

There are several Java canvases to show data in 2D: jhplot.Plot jhplot.Plot, jhplot.HPlot jhplot.HPlot,jhplot.HPlotJa jhplot.HPlotJa, jhplot.SPlot jhplot.SPlot, jhplot.HPlotXY jhplot.HPlotXY.

Below we discuss canvases which can be used to display data in 2D. Such canvases usually have the names starting with the capital "H".

The code shown below creates a canvas with the size 600x400 (in pixels), it has 2 pads to show data. The method visible(100,200) make the canvas visible and sets its location on the screen at position 100 (in X from left corner) and 200 (from top) in pixels. If you want a default position, jut call "visible()". Then you can draw any mathematical object or data. Then you can export the image to vector format. See the jhplot.HPlot jhplot.HPlot documentation. It should be noted the jhplot.HPlot jhplot.HPlot canvas can be replaced by any other canvas described above.

Typically, you can build a plot to show 2D data as this:

Exporting to images

When DMelt functions, histograms, data structures are shown, one can create an image using the menu [File]-[Export]. One can also save image in a file using the method "export(file)" to a variety of vector graphics formats as well as bitmap image formats.

In the example below, we save an instance of the HPlot class to a PDF file:

c1.export('image.pdf')

we export drawings on the canvas HPlot (c1 represents its instance) into a PDF file. One can also export it into PNG, JPEG, EPS, PS etc. formats using the appropriate extension for the output file name.

As example, simply append the statement "c1.export('image.ps')" at the end of code, and your image will be saved to a PostScript file "image.ps".

Images can be generated in a background (without a pop-up frame with the canvas). For this, use the method "c1.visible(0)", where "0" means Java false.

Different plot styles

Line plots

Line chart Line chart is a chart which displays information as a series of data points called 'markers' connected by straight line segments.

DMelt example: Line chart with categories

with the code

from jhplot  import *

c1 = HChart("Canvas")
c1.visible()

c1.setChartLine()
c1.setName("Line chart")
c1.valueLine(1.0, "First", "category1");
c1.valueLine(2.0, "First", "category2");
c1.valueLine(10.0, "First", "category3");
c1.valueLine(8.0, "First", "category3");

c1.valueLine(3.0, "Second", "category1");
c1.valueLine(2.8, "Second", "category2");
c1.valueLine(4.0, "Second", "category3");
c1.valueLine(1.0, "Second", "category3");
c1.update()
# c1.export("a.pdf")

Histograms

To make a plot of a histogram histogram, you need to make a histogram which is an object on its own. Typically, you need to create an obejct using jhplot.H1D jhplot.H1D. Some examples of how to deal with histograms are considered in Sect. DScience:Histograms. Typiaclly, histograms are used to show some numerical values such that X-axis is numeric.

from java.awt import Color,Font
from java.util import Random
from jhplot import *

c1 = HPlot("Canvas",600,400)
c1.getAntiAlias()
c1.setGTitle("Title")
c1.visible()

# set range
# c1.setRange(-4,4,0.0,100)
# set autorange
c1.setAutoRange()

h1 = H1D("e^{+}e^{-} → W^{+}W^{-} → 4 jets",20, -2.0, 2.0)
rand = Random()
# fill histogram
for i in range(500):
      h1.fill(rand.nextGaussian())

h1.setFill(1)
h1.setFillColor(Color.green)
h1.setErrX(0)
h1.setErrY(1)
h1.setPenWidthErr(2)

# h1.toTable()

h2 = H1D("e^{+}e^{-} → Z/γ →  hadrons ",15, -2.0, 2.0)
h2.setFill(1)
h2.setErrX(0)
h2.setErrY(1)
h2.setFillColorTransparency(0.7)
h2.setFillColor(Color.red)
h2.setColor(Color.red)
h2.setErrColorY(Color.blue)
h2.setNameX("X of H2")
h2.setNameY("Y of H2")

for i in range(1000): 
      h2.fill(2+rand.nextGaussian())



c1.setLegendFont( Font("Lucida Sans", Font.BOLD, 18)  )
c1.setNameX("Text Examples:− θ π ω ∫ ∑")
c1.setNameY("Yaxis")
c1.setName("Canvas title: √(1− e)")

c1.draw(h1)
c1.draw(h2)


# export to some image (png,eps,pdf,jpeg...)
# c1.export(Editor.DocMasterName()+".png");
# edit the image
# IEditor(Editor.DocMasterName()+".png");

The output will be shown as:

DMelt example: H1D histograms with some style

Bar charts

Bar chart Bar chart are similar to histogram histograms. The bar chart shows categorical data with rectangular bars with heights or lengths proportional to the values that they represent, thus the bar charts are similar to histogram representation of data. The bars can be plotted vertically or horizontally. Thus, the histogram representation is a special case of bar charts.

An example of bar chart is shown here:

DMelt example: Show GDP / capita from CVS file using WorldBank data

# Download CVS file from https://data.worldbank.org/indicator/NY.GDP.PCAP.CD
# The file should have the name ny.gdp.pcap.cd_Indicator_en_csv_v2.csv
from jhplot.io.csv import *
from java.io import *
from jhplot import *
import urllib
urllib.urlretrieve ("https://datamelt.org/examples/data/ny.gdp.pcap.cd_Indicator_en_csv_v2.csv", "tmp.csv")

dict={}  
reader =CSVReader(FileReader("tmp.csv"));
while True:
      nextLine = reader.readNext()
      if nextLine== None: break
      xlen=len(nextLine)
      if  xlen<50: continue
      dict[nextLine[0]]=nextLine[xlen-2] # key: country, vaue=DGP
c1 = HChart("2013",800,400)
#c1.setGTitle("2013 Gross domestic product  per capita")
c1.visible()
c1.setChartBar()
c1.setNameY("current US $")
c1.setNameX("") 
c1.setName("2013 Gross domestic product  per capita")
name1="Data Source: World Development Indicators"
name="Russia"; c1.valueBar(float(dict[name]) ,name,name1)
name="Poland"; c1.valueBar(float(dict[name]) ,name,name1)
name="Romania"; c1.valueBar(float(dict[name]) ,name,name1)
name="Bulgaria"; c1.valueBar(float(dict[name]) ,name,name1)
name="Belarus"; c1.valueBar(float(dict[name]) ,name,name1)
name="Ukraine"; c1.valueBar(float(dict[name]) ,name,name1)
c1.update()


Pie Chart

Pie chart Pie chart is a circular gpaph which is divided into slices. The slices illustrate numerical proportion such that the arc length of each slice is proportional to the quantity it represents. It is named for its resemblance to a pie.

DMelt example: A pie chart using jFreeChart


from org.jfree.chart import ChartFactory
from org.jfree.data.general import DefaultPieDataset
from jhplot import HPlotChart

piedataset =DefaultPieDataset()
piedataset.setValue("Apr", 10)
piedataset.setValue("May", 30)
piedataset.setValue("June", 40)

chart = ChartFactory.createPieChart("Pie Chart",piedataset,1,1,1)
c1 = HPlotChart( chart )
c1.visible()

Discrete data points

Such plots typically shows position of points in X-Y. In a simple case, they can be made as this:

DMelt example: Data points using SPlot

from java.awt import Color,Font
from java.util import Random
from jhplot  import *
from jhplot.math.StatisticSample import randUniform


c1 = SPlot("Test",600,400)
c1.visible()

c1.draw( "set 1", randUniform(1000,0.0,100.0),
         randUniform(1000,0.0,100.0) )

c1.draw( "set 2", randUniform(500,40.0,80.0),
         randUniform(500,20.0,80.0) )

Generally, if you need to show error bars in X or Y, use jhplot.P1D jhplot.P1D data containers (will be discussed later).

Polar plots

For the polar coordinates, use the jhplot.HChart jhplot.HChart canvas. A small code below shows ho to show a dataset filled from the X-Y array jhplot.P1D jhplot.P1D

from java.awt import Color
from java.awt import Font
from java.util import Random
from math  import *
from jhplot import HChart,P1D

c1 = HChart("Canvas",600,500, 2, 1)
c1.setGTitle("Polar coordinates")
c1.visible()

c1.cd(1,1)
c1.setName("Polar coordinates-I")
c1.setChartPolar()
p1= P1D("test 1")
p2= P1D("test 2")
# fill
rand = Random() 
for i in range(20):
      x=4.0*i # x-value
      p1.add(i*4, 10.0*rand.nextGaussian());
      p2.add(i*2, 5.0*rand.nextGaussian());
c1.add(p1)
#c1.add(p2)
c1.update()

c1.cd(2,1)
p3= P1D("Example")
for i in range(0,3*360,5):
    p3.add( 90-i,i)
c1.setChartPolar()
c1.setName("Polar coordinates-II")
c1.add(p3)
c1.update()

# export to some image (png,eps,pdf,jpeg...)
# c1.export(Editor.DocMasterName()+".png")

DMelt example: Charts using polar coordinates


Contour plots

Density plots

You can also make density plots in which color represent density (or values). Look at this rather comprehensive example which shows how to plot F2D functions or 2D histograms (H2D) using several pads:

from java.awt import Color
from jhplot import *

c1 = HPlot3D('Canvas',600,600)
c1.setNameX('X')
c1.setNameY('Y')
c1.setContour()
c1.visible()
c1.setAutoRange()
f1=F2D('(0.5*x)^2+y^2', -2.0, 2.0, -2.0, 2.0)
c1.draw(f1)

DMelt example: Function using a HPlot3D canvas with a contour style


Vector fields

Showing shapes and objects

You can show data and functions together with different 2D objects. Here is a simple example that shows a histogram, a data set in X-Y and 3 ellipses:

from java.awt import Font,BasicStroke,Color
from java.util import Random
from jhplot import HLabel, HPlot 
from jhplot.shapes  import *

# make empty canvas in some range
c1 =HPlot("Canvas",600,400)
c1.setGTitle("HShape package to draw Java 2D objects")
c1.setLegend(0)
c1.setNameX("X")
c1.setNameY("Y")
c1.setRange(-4.0, 4.0, 0.0, 20.0)
c1.visible(1)

# show a line in the NDC system
line = Line(0.1,0.9, 0.2, 0.9)
line.setPosCoord("NDC")
line.setColor(Color.red)
line.setTransparency(0.5)
c1.add(line)

#show a line in the NDC system
line = Line(0.1,0.85, 0.2, 0.85);
line.setDashed(3.0);
line.setPosCoord("NDC");
line.setColor(Color.blue);
line.setTransparency(0.5);
c1.add(line);

# show dotted line in the USER system
line = Line(-2.0, 10, -1.0, 12.0)
line.setDotted(2.0)
line.setColor(Color.magenta)
line.setTransparency(0.5)
c1.add(line)


# arrow
arr = Arrow(-2, 2, -2, 10)
c1.add(arr)

# arrow in the NDC system
arr = Arrow(0.85, 0.5, 0.85, 0.7)
arr.setColor(Color.blue)
arr.setPosCoord("NDC")
stroke = BasicStroke(5.0)
arr.setStroke(stroke)
arr.setType(2)
c1.add(arr)

# arrow in the NDC system
arr = Arrow(-2.0, 4.6, -2.5, 8.0)
arr.setColor(Color.black)
stroke = BasicStroke(1.0)
arr.setStroke(stroke)
arr.setType(3)
c1.add(arr)


# arrow in the NDC system
arr = Arrow(-3.0, 2.6, -2.0, 10.7)
arr.setColor(Color.black)
stroke = BasicStroke(1.0)
arr.setStroke(stroke)
arr.setType(1)
c1.add(arr)




tex=  Text("This is a text",-2.4, 12)
c1.add(tex)


cic= Circle(-0.5, 10, 2.0)
cic.setFill(1)
cic.setColor(Color.red)
cic.setTransparency(0.5)
c1.add(cic)


# filled eclipse
ele= Ellipse(-1.2, 8, 1.0, 0.9)
ele.setFill(1)
ele.setColor(Color.green)
ele.setTransparency(0.8)
c1.add(ele)


# show circle
cic=Circle(-0.9, 11, 1.5)
cic.setFill(0)
c1.add(cic)


# rectangle
rec=Rectan(0.0, 10.0, 0.9, 1.2);
rec.setFill(1);
c1.add(rec);


rec= Rectan(2.0, 3.0, 2.9, 1.6);
rec.setFill(1);
rec.setColor(Color.yellow);
rec.setTransparency(0.7);
c1.add(rec);


# set HLabel in the USER coordinate system
lab=HLabel("HLabel in USER", -2, 10);
c1.add(lab);


# set HLabel in the normilised coordinate system
lab=HLabel("HLabel in NDC", 0.5, 0.2, "NDC");
c1.add(lab);

# now show all objects
c1.update();



# export to some image (png,eps,pdf,jpeg...)
# c1.export(Editor.DocMasterName()+".png");

Here is the output of this example:

DMelt example: Show basic shapes (Line, Circle, image)

Post editing

jhplot.HPlotJa jhplot.HPlotJa can be used to edit figures. For example, one can make inserts if one creates 2 plotting pads and then one can edit the pads using the "mouse-click" fashion. For example, run this script:

from java.awt import Color,Font
from java.util import Random
from jhplot  import P1D
from jhplot  import HPlotJa
 
c1 = HPlotJa("Canvas",800,600,2,1)
c1.visible()
c1.setAutoRange()

x=10
y=20
xLeft=2
xRight=2
yLower=3
yUpper=3
xLeftSys=5
xRightSys=3
yUpperSys=3
xLowerSys=3

p1=P1D("TEST")
p1.add(x,y,xLeft,xRight,yUpper,yLower,xLeftSys,xRightSys,yUpperSys,xLowerSys);
p1.setErrTicSize(20)
p1.setPenWidthErrSys(2)
p1.setPenWidthErr(4)
p1.setStyle("p")
p1.setErr(1)
p1.setErrSys(1)
p1.setColor(Color.black)
p1.setSymbolSize(7)
c1.draw(p1)
c1.update()

# export to some image (png,eps,pdf,jpeg...)
# c1.export(Editor.DocMasterName()+".png")

Then edit the figure (increase the size of one pad, and then drag the other one):

DMelt example: HPlotJa shows data points with errors

Similarly, one can achieve the same using the method "setPad()" where you can specify the location and the sizes of the plot regions The script below creates 2 plotting pads. The second pad is located inside the first one. Then you can plot data as usual, navigating to certain pads using the "cd(i,j)" method.

Several plotting regions

These canvases can be used to show several pads (plot regions) with plotted objects. Specify the number of divisions in X and Y in the constructors. The navigate to a specific plot region using the method "cd()". Here is example of how to create 2x2 pads on a single canvas:

from jhplot  import *

c1 = HPlot("Canvas",500,400,2,2)
c1.visible()
c1. setRangeAll(0,10,0,10)
h1 = P1D("Simple")

c1.cd(1,1)
h1.add(5,6);  c1.draw(h1)

c1.cd(1,2)
h1.add(4,3); c1.draw(h1)

c1.cd(2,1)
h1.add(3,3); c1.draw(h1)

c1.cd(2,2)
h1.add(2,1); c1.draw(h1)
c1.export ("example.pdf") # export to PDF

DMelt example: Shwoing X-Y data on 4 canvas regions

This works for jhplot.HPlot jhplot.HPlot, jhplot.HPlotJa jhplot.HPlotJa, jhplot.HPlot3D jhplot.HPlot3D and many other pads.

Here we use the same X and Y ranges. One can use "setAutoRange()" (after each "cd()") method to set autorange for each pad. Also, try "setRange(xmin,xmax,ymin,ymax)" to set fixed ranges for each pads. it shows 4 pads with data points.

The plots are fully customizable, i.e. one can change any attribute (axis, label, ticks, ticks label).

Interactive plotting

jhplot.HPlotJas jhplot.HPlotJas canvas represents a way to prepare all objects for plotting, fitting and rebinning of data.


Axis labels

Can be set using setNameX("label") and setNameY("label"). These are global methods which should be applied to the HPlot canvas. However, every plotting object have their own methods, such as "setLabelX("label")" and setLabelY("label")". If the labels are set to the object, the plot will display the object labels rather than those set using setNameX() and setNameY().

Ticks and subticks

One can redefine ticks using several methods of the jhplot.HPlot jhplot.HPlot

The simple example illustrates this:

from jhplot  import *

c1 = HPlot("Canvas")
c1.visible()
c1.setRange(0,10,0,10)
c1.setNumberOfTics(0,2) 
c1.setNumberOfTics(1,5)
c1.setSubTicNumber(0,2)
c1.setSubTicNumber(1,4)

h1 = P1D("Simple1")
xpos=5
ypos=7
h1.add(xpos,ypos)
c1.draw(h1)

lab=HLabel("Point", xpos, ypos, "USER")
c1.add(lab)
c1.update()
c1.export ("example.pdf")

We labeled a point and generated a PDF files with the figure as shown in this figure:

DMelt example: Show ticks and custom labels with annotations

Embedding in JFrame

It is possible to embed DataMelt canvases in Java java.swing.JFrame java.swing.JFrame, so you can build an application with custom buttons. Here is an example:

from jhplot import *
c1=HPlot("GUI")
fr=c1.getFrame()
# .. fill c1 frame with data (H1D,P1D)
# do what you like to do, i.e. add any component
# then 
fr.pack()

Using GROOT

DMelt includes GROOT package developed at JLab. Its syntax reminds the PyROOT environment. You can find example in Jython and Java here:

Waterloo scientific charts

DataMelt allows to access reach Waterloo scientific graphics package implemented in Java. The original web page is [1]. However, DataMelt only used the base of the Waterloo package. A support for Groovy and Jython is done via the internal DataMelt api.

The API of these Java libraries for scientific plotting can be found Waterloo graphics package Waterloo graphics package. Let us give a small example of X-Y plot:

# This example shows how to plot X-Y using Waterloo scientific library 

from kcl.waterloo.swing import GCFrame
from kcl.waterloo.graphics import GJGraph,GJGraphContainer
from kcl.waterloo.graphics.plots2D import GJScatter,GJPlotInterface

f=GCFrame("Scatter plot")
gc=GJGraphContainer.createInstance(GJGraph.createInstance())
f.add(gc)

x=[]
y=[]
for i in range(-100,100,5):
      x.append(i)
      y.append(i*i)

p=GJScatter.createInstance()
p.setXData(x)
p.setYData(y)

gc.getView().add(p)
gc.getView().autoScale()

print "Creating SVG image.."
from kcl.waterloo.export import ExportFactory
from java.io import File
ExportFactory.saveAsSVG(gc, File("canvas2D_points_waterloo.svg"))

This plot shows the function x*x as shown below:

DMelt example: Plotting X-Y using Waterloo scientific library

This tutorial is provided under this license agreement.