Package ptolemy.plot

Class Histogram

  • All Implemented Interfaces:
    java.awt.image.ImageObserver, java.awt.MenuContainer, java.awt.print.Printable, java.io.Serializable, javax.accessibility.Accessible, PlotBoxInterface

    public class Histogram
    extends PlotBox
    A histogram plotter. The plot can be configured and data can be provided either through a file with commands or through direct invocation of the public methods of the class. To read a file or a URL, use the read() method.

    When calling the public methods, in most cases the changes will not be visible until paint() has been called. To request that this be done, call repaint(). One exception is addPoint(), which makes the affect of the new point visible immediately (or nearly immediately) if the plot is visible on the screen.

    The ASCII format for the file file contains any number commands, one per line. Unrecognized commands and commands with syntax errors are ignored. Comments are denoted by a line starting with a pound sign "#". The recognized commands include those supported by the base class, plus a few more. The commands are case insensitive, but are usually capitalized. The number of data sets to be plotted does not need to be specified. Data sets are added as needed. Each dataset is identified with a color (see the base class).

    The appearance of the histogram can be altered by the following commands:

     Bars: width
     Bars: width, offset
     
    The width is a real number specifying the width of the bars as a fraction of the bin width. It usually has a value less than or equal to one, and defaults to 0.5. The offset is a real number specifying how much the bar of the i th data set is offset from the previous one. This allows bars to "peek out" from behind the ones in front. It defaults to 0.15. Note that the frontmost data set will be the first one.

    The width of each bin of the histogram can be specified using:

     BinWidth: width
     
    This is given in whatever units the data has. By default, each bin is centered at x = nw, where w is the width of the bin and n is an integer. That bin represents values in the range (x - w/2, x + w/2). The alignment of the bins can be changed with the following command:
     BinOffset: offset
     
    If this method is used with argument o, then each bin is centered at x = nw + o, and represents values in the range (x - w/2 + o, x + w/2 + o). So for example, if o = w/2, then each bin represents values from nw to (n + 1)w for some integer n. The default offset is 0.5, half the default bin width.

    To specify data to be plotted, start a data set with the following command:

     DataSet: string
     
    Here, string is a label that will appear in the legend. It is not necessary to enclose the string in quotation marks. To start a new dataset without giving it a name, use:
     DataSet:
     
    In this case, no item will appear in the legend. New datasets are plotted behind the previous ones. The data itself is given by a sequence of numbers, one per line. The numbers are specified as strings that can be parsed by the Double parser in Java. It is also possible to specify the numbers using all the formats accepted by the Plot class, so that the same data may be plotted by both classes. The x data is ignored, and only the y data is used to calculate the histogram.
    Since:
    Ptolemy II 0.3
    Version:
    $Id$
    Author:
    Edward A. Lee, Contributor: Bert Rodiers
    See Also:
    Serialized Form
    Pt.AcceptedRating:
    Yellow (cxh)
    Pt.ProposedRating:
    Yellow (cxh)
    • Nested Class Summary

      • Nested classes/interfaces inherited from class javax.swing.JPanel

        javax.swing.JPanel.AccessibleJPanel
      • Nested classes/interfaces inherited from class javax.swing.JComponent

        javax.swing.JComponent.AccessibleJComponent
      • Nested classes/interfaces inherited from class java.awt.Container

        java.awt.Container.AccessibleAWTContainer
      • Nested classes/interfaces inherited from class java.awt.Component

        java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy
    • Constructor Summary

      Constructors 
      Constructor Description
      Histogram()  
    • Method Summary

      All Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      protected void _checkDatasetIndex​(int dataset)
      Check the argument to ensure that it is a valid data set index.
      protected void _drawBar​(java.awt.Graphics graphics, int dataset, long xpos, long ypos, boolean clip)
      Draw bar from the specified point to the y axis.
      protected void _drawPlot​(java.awt.Graphics graphics, boolean clearfirst, java.awt.Rectangle drawRect)
      Draw the axes and then plot the histogram.
      protected boolean _parseLine​(java.lang.String line)
      Parse a line that gives plotting information.
      protected void _resetScheduledTasks()
      Reset a scheduled redraw tasks.
      protected void _scheduledRedraw()
      Perform a scheduled redraw.
      void addLegend​(int dataset, java.lang.String legend)
      Add a legend (displayed at the upper right) for the specified data set with the specified string.
      void addPoint​(int dataset, double value)
      In the specified data set, add the specified value to the histogram.
      void addPoint​(int dataset, double x, double y, boolean connected)
      In the specified data set, add the specified y value to the histogram.
      void clear​(boolean format)
      Clear the plot of all data points.
      void exportToPlot​(java.io.PrintWriter output, java.lang.String dtd)
      Write plot data information to the specified output stream in PlotML, but in such a way that the Plot class can read it and reproduce the histogram.
      void fillPlot()
      Rescale so that the data that is currently plotted just fits.
      void samplePlot()
      Create a sample plot.
      void setBars​(double width, double offset)
      Set the width and offset of the bars.
      void setBinOffset​(double offset)
      Set the offset of the bins, in whatever units the data are given.
      void setBinWidth​(double width)
      Set the width of the bins, in whatever units the data are given.
      void setSeed​(java.lang.Long seed)
      Set the seed of the random number generator used to create the sample plot.
      void write​(java.io.Writer out, java.lang.String dtd)
      Write the current data and plot configuration to the specified stream in PlotML syntax.
      void writeData​(java.io.PrintWriter output)
      Write plot data information to the specified output stream in PlotML.
      void writeFormat​(java.io.PrintWriter output)
      Write plot format information to the specified output stream.
      • Methods inherited from class javax.swing.JPanel

        getAccessibleContext, getUI, getUIClassID, paramString, setUI, updateUI
      • Methods inherited from class javax.swing.JComponent

        addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, hide, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingOrigin, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setFont, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update
      • Methods inherited from class java.awt.Container

        add, add, add, add, add, addContainerListener, addImpl, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusDownCycle, validate, validateTree
      • Methods inherited from class java.awt.Component

        action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, requestFocus, requestFocus, requestFocusInWindow, resize, resize, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setMixingCutoutShape, setName, setSize, show, show, size, toString, transferFocus, transferFocusBackward, transferFocusUpCycle
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
    • Field Detail

      • _currentdataset

        protected int _currentdataset
        The current dataset.
      • _points

        protected java.util.Vector _points
        A vector of datasets.
      • _histogram

        protected java.util.Vector _histogram
        A vector of histogram data.
    • Constructor Detail

      • Histogram

        public Histogram()
    • Method Detail

      • addLegend

        public void addLegend​(int dataset,
                              java.lang.String legend)
        Add a legend (displayed at the upper right) for the specified data set with the specified string. Short strings generally fit better than long strings.
        Specified by:
        addLegend in interface PlotBoxInterface
        Overrides:
        addLegend in class PlotBox
        Parameters:
        dataset - The dataset index.
        legend - The label for the dataset.
        See Also:
        PlotBox.renameLegend(int, String)
      • addPoint

        public void addPoint​(int dataset,
                             double value)
        In the specified data set, add the specified value to the histogram. Data set indices begin with zero. If the data set does not exist, create it. The new point will visibly alter the histogram if the plot is visible on the screen. Otherwise, it will be drawn the next time the histogram is drawn on the screen.

        In order to work well with swing and be thread safe, this method actually defers execution to the event dispatch thread, where all user interface actions are performed. Thus, the point will not be added immediately (unless you call this method from within the event dispatch thread). All the methods that do this deferring coordinate so that they are executed in the order that you called them.

        Parameters:
        dataset - The data set index.
        value - The new value.
      • addPoint

        public void addPoint​(int dataset,
                             double x,
                             double y,
                             boolean connected)
        In the specified data set, add the specified y value to the histogram. The x value and the connected arguments are ignored. Data set indices begin with zero. If the data set does not exist, create it.
        Parameters:
        dataset - The data set index.
        x - Ignored.
        y - The Y position of the new point.
        connected - Ignored
      • clear

        public void clear​(boolean format)
        Clear the plot of all data points. If the argument is true, then reset all parameters to their initial conditions, including the persistence, plotting format, and axes formats. For the change to take effect, you must call repaint().

        In order to work well with swing and be thread safe, this method actually defers execution to the event dispatch thread, where all user interface actions are performed. Thus, the clear will not be executed immediately (unless you call this method from within the event dispatch thread). All the methods that do this deferring coordinate so that they are executed in the order that you called them.

        Specified by:
        clear in interface PlotBoxInterface
        Overrides:
        clear in class PlotBox
        Parameters:
        format - If true, clear the format controls as well.
      • exportToPlot

        public void exportToPlot​(java.io.PrintWriter output,
                                 java.lang.String dtd)
        Write plot data information to the specified output stream in PlotML, but in such a way that the Plot class can read it and reproduce the histogram. The ordinary mechanism for saving the histogram records the raw data and the configuration to be used by this class.
        Parameters:
        output - A buffered print writer.
        dtd - The DTD, or null to reference the default.
      • fillPlot

        public void fillPlot()
        Rescale so that the data that is currently plotted just fits. This overrides the base class method to ensure that the fill is actually performed in the event dispatch thread. In order to work well with swing and be thread safe, this method actually defers execution to the event dispatch thread, where all user interface actions are performed. Thus, the fill will not occur immediately (unless you call this method from within the event dispatch thread). All the methods that do this deferring coordinate so that they are executed in the order that you called them.
        Specified by:
        fillPlot in interface PlotBoxInterface
        Overrides:
        fillPlot in class PlotBox
      • setBars

        public void setBars​(double width,
                            double offset)
        Set the width and offset of the bars. Both are specified as a fraction of a bin width. The offset is the amount by which the i th data set is shifted to the right, so that it peeks out from behind the earlier data sets.
        Parameters:
        width - The width of the bars.
        offset - The offset per data set.
      • setBinOffset

        public void setBinOffset​(double offset)
        Set the offset of the bins, in whatever units the data are given. Without calling this, each bin is centered at x = nw, where w is the width of the bin and n is an integer. That bin represents values in the range (x - w/2, x + w/2). If this method is called with argument o, then each bin is centered at x = nw + o, and represents values in the range (x - w/2 + o, x + w/2 + o). So for example, if o = w/2, then each bin represents values from nw to (n + 1)w) for some integer n.
        Parameters:
        offset - The bin offset.
      • setBinWidth

        public void setBinWidth​(double width)
        Set the width of the bins, in whatever units the data are given.
        Parameters:
        width - The width of the bins.
      • setSeed

        public void setSeed​(java.lang.Long seed)
        Set the seed of the random number generator used to create the sample plot. This method is primarily used for testing.
        Parameters:
        seed - The seed.
        See Also:
        samplePlot()
      • write

        public void write​(java.io.Writer out,
                          java.lang.String dtd)
        Write the current data and plot configuration to the specified stream in PlotML syntax. This writes the histogram, not the raw data, in such a way that the Plot class (not the Histogram class) will correctly render it. The URL (relative or absolute) for the DTD is given as the second argument. If that argument is null, then the PlotML PUBLIC DTD is referenced, resulting in a file that can be read by a PlotML parser without any external file references, as long as that parser has local access to the DTD. The output is buffered, and is flushed before exiting.
        Specified by:
        write in interface PlotBoxInterface
        Overrides:
        write in class PlotBox
        Parameters:
        out - An output writer.
        dtd - The reference (URL) for the DTD, or null to use the PUBLIC DTD.
      • writeData

        public void writeData​(java.io.PrintWriter output)
        Write plot data information to the specified output stream in PlotML.
        Specified by:
        writeData in interface PlotBoxInterface
        Overrides:
        writeData in class PlotBox
        Parameters:
        output - A buffered print writer.
      • writeFormat

        public void writeFormat​(java.io.PrintWriter output)
        Write plot format information to the specified output stream.
        Specified by:
        writeFormat in interface PlotBoxInterface
        Overrides:
        writeFormat in class PlotBox
        Parameters:
        output - A buffered print writer.
      • _checkDatasetIndex

        protected void _checkDatasetIndex​(int dataset)
        Check the argument to ensure that it is a valid data set index. If it is less than zero, throw an IllegalArgumentException (which is a runtime exception). If it does not refer to an existing data set, then fill out the _points and _histogram Vectors so that they refer to all existing data sets.
        Parameters:
        dataset - The data set index.
      • _drawBar

        protected void _drawBar​(java.awt.Graphics graphics,
                                int dataset,
                                long xpos,
                                long ypos,
                                boolean clip)
        Draw bar from the specified point to the y axis. If the specified point is below the y axis or outside the x range, do nothing. If the clip argument is true, then do not draw above the y range. Note that paint() should be called before calling this method so that _xscale and _yscale are properly set.
        Parameters:
        graphics - The graphics context.
        dataset - The index of the dataset.
        xpos - The x position.
        ypos - The y position.
        clip - If true, then do not draw outside the range.
      • _drawPlot

        protected void _drawPlot​(java.awt.Graphics graphics,
                                 boolean clearfirst,
                                 java.awt.Rectangle drawRect)
        Draw the axes and then plot the histogram. If the second argument is true, clear the display first. This method is called by paint(). To cause it to be called you would normally call repaint(), which eventually causes paint() to be called.

        Note that this is synchronized so that points are not added by other threads while the drawing is occurring. This method should be called only from the event dispatch thread, consistent with swing policy.

        Overrides:
        _drawPlot in class PlotBox
        Parameters:
        graphics - The graphics context.
        clearfirst - If true, clear the plot before proceeding.
        drawRect - A specification of the size.
      • _parseLine

        protected boolean _parseLine​(java.lang.String line)
        Parse a line that gives plotting information. Return true if the line is recognized. Lines with syntax errors are ignored.
        Overrides:
        _parseLine in class PlotBox
        Parameters:
        line - A command line. It is not synchronized, so its caller should be.
        Returns:
        True if the line is recognized.
      • _resetScheduledTasks

        protected void _resetScheduledTasks()
        Reset a scheduled redraw tasks.
        Overrides:
        _resetScheduledTasks in class PlotBox
      • _scheduledRedraw

        protected void _scheduledRedraw()
        Perform a scheduled redraw.
        Overrides:
        _scheduledRedraw in class PlotBox