dflplot
dflplot
is a plotting library based on DFL, and is geared towards
generating simple plots in scientific and statistical computing use
cases. Right now it's a work in progress, but is good enough to be
useful for simple exploratory plotting in scientific computing contexts,
especially with other scientific computing libraries like dstats and SciD.
Known Issues:
1. Rotated text for Y-Axis labels isn't available in DFL. Therefore,
Y-Axis labels are rendered in ugly columnar text.
2. There is currently no "proper" way to save a plot. This is because
DFL's Bitmap object doesn't provide a way to obtain the underlying
pixels yet, and core.stdc.windows doesn't seem to provide the necessary
stuff to do it manually via the Windows API. In the meantime, a
workaround (at least for manual, as opposed to programmatic, saving)
is to take a screenshot using the print screen key and save
this.
3. No options (such as axis limits, title, labels, etc.) are exposed yet
via the plot window GUI. This situation will be improved gradually,
especially as DFL improves.
4. Only works on Windows. Eventually, I'll abstract away a bunch of the
GUI logic and port this to gtkD when it matures, or (hopefully)
DFL will be ported to Linux.
Copyright (C) 2010 David Simcha
License:
Boost Software License - Version 1.0 - August 17th, 2003
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
- Color
getColor
(ubyte red, ubyte green, ubyte blue);
- Get a color w/o having to import or directly interact with the GUI framework.
Adding this is in preparation for porting to another GUI framework.
- struct
FigureLine
;
- For drawing extra lines on a Figure, with coordinates specified in plot
units and relative to the plot area, not in pixels.
- class
Figure
: dfl.control.Control;
- A container form for one or more Plot objects.
Examples:
auto nums = [1,1,1,1,2,2,3,3,4,5,6,7];
auto hist = Histogram(nums, 10);
auto fig = new Figure;
fig.addPllot(hist);
fig.title = "A plot";
fig.xLabel = "X label";
fig.yLabel = "Y label";
fig.showAsMain();
- static Figure
opCall
();
- static Figure
opCall
(Plot[] plots...);
- Convenience factory that adds all plots provided to the Figure.
- string
title
;
- string
xLabel
;
- string
yLabel
;
- Font
titleFont
;
- Default:
Veranda 14
- Font
xLabelFont
;
- Default:
Veranda 14
- Font
yLabelFont
;
- Default:
Veranda 14
- Font
axesFont
;
- Default:
Veranda 10
- Figure
xLim
(double newLower, double newUpper);
- Manually set the X axis limits.
- Figure
yLim
(double newLower, double newUpper);
- Manually set the Y axis limits.
- Figure
xTickLabels
(R)(R locations, const string[] text = null);
- Set the X axis labels. If text is null (default) the axis text is
just the text of the axis locations. R should be any range with
length identical to text (unless text is null) and elements implicitly
convertible to double.
- Figure
yTickLabels
(R)(R locations, const string[] text = null);
- Set the Y axis labels. If text is null (default) the axis text is
just the text of the axis locations. R should be any range with
length identical to text (unless text is null) and elements implicitly
convertible to double.
- bool
horizontalGrid
;
- Determines whether horizontal gridlines are drawn. Default is false.
- bool
verticalGrid
;
- Determines whether vertical gridlines are drawn. Default is false.
- @property double
leftMost
();
- The leftmost point on the figure.
- @property double
rightMost
();
- The rightmost point on the figure.
- @property double
topMost
();
- The topmost point on the figure.
- @property double
bottomMost
();
- The bottommost point on the figure.
- Figure
addLines
(FigureLine[] lines...);
- Add individual lines to the figure. Coordinates are specified relative
to the plot area, not in pixels. The lines are is clipped
to the visible part of the plot area. This is useful for adding
annotation lines, as opposed to plot lines.
- Figure
addPlot
(Plot[] plots...);
- Add one or more plots to the figure.
- void
drawPlot
();
- Draw the plot but don't display it on screen.
- void
showAsMain
();
- Draw and display the figure as a main form. This is useful in
otherwise console-based apps that want to display a few plots.
However, you can't have another main form up at the same time.
- class
Subplot
: dfl.form.Form;
- Allows for one or more subplots to be created in a single window. Each
subplot is represented by a Figure. Double-clicking on any subplot zooms
in on it. Double-clicking again zooms out.
Note:
When this class is passed a Figure, it assumes complete ownership of
that Figure and will feel free to mess around with its internal state.
Examples:
auto hist = Histogram(someNumbers, 10);
auto histFig = new Figure(hist);
auto scatter = ScatterPlot(someNumbers, someMoreNumbers);
auto scatterFig = new Figure(scatter);
auto sub = new SubPlot(1, 2); // 1 row, 2 columns.
sub.addPlot(histFig, 0, 0); // Add the histogram in the 0th row, 0th column.
sub.addPlot(scatterFig, 0, 1); // Ditto.
sub.show();
- string
title
;
- Main
title
of the plot. The subplots may also have titles.
- string
xLabel
;
- Main x label of the plot. The subplots may also have x labels.
- string
yLabel
;
- Main y label of the plot. The subplots may also have y labels.
- static Subplot
opCall
(uint nRows, uint nColumns);
- Create an instance with nRows rows and nColumns columns.
- Subplot
addFigure
(ref Figure fig, uint row, uint col);
- Add a figure to the subplot in the given row and column. fig is passed
in by reference, and the handle passed in is set to null. This is
to emphasize the fact that the Subplot class assumes ownership of the
figure class and is free to modify the Figure's internal state.
This function returns this to allow for a fluent interface.
- final void
addFigure
(Figure fig, uint row, uint col);
- Convenience function in case fig isn't an lvalue.
- void
drawFigure
();
- Draw the figure, but don't display it.
- void
showAsMain
();
- Draw and display the figure as a main form. This is useful in
otherwise console-based apps that want to display a few plots.
However, you can't have another main form up at the same time.
- abstract class
Plot
;
- Abstract base class for all types of plot objects.
- @property Figure
toFigure
();
- Convenience method that instantiates a Figure object with this plot.
Useful for creating single-plot figures w/o a lot of boilerplate.
Examples:
auto hist = Histogram([1,2,3,4,5], 3).toFigure;
hist.showAsMain();
- @property Figure
toLabeledFigure
();
- Instantiates a Figure object with this plot and also places the default
axes and tick labeling and title for the plot type, if any, on the
Figure. If a plot type has no default labeling, simply forwards to
toFigure().
- @property double
leftMost
();
- The leftmost point on the plot.
- @property double
rightMost
();
- The rightmost point on the plot.
- @property double
topMost
();
- The topmost point on the plot.
- @property double
bottomMost
();
- The bottommost point on the plot.
- class
BarPlot
: dflplot.Plot;
- A basic bar plot.
- Color
barColor
;
- Controls the color of the bar. Defaults to blue.
- immutable double
width
;
- BarPlot
opCall
(R1, R2)(R1 centers, R2 heights, double width);
- Create a BarPlot. centers and heights must be input ranges with elements
implicitly convertible to double. width determines the width of each
bar relative to the X-axis scale and must be greater than 0.
- BarPlot
opCall
(R1, R2, R3, R4)(R1 centers, R2 heights, double width, R3 lowerErrors, R4 upperErrors);
- Create a BarPlot with error bars. lowerErrors and upperErrors
must be input ranges with elements implicitly convertible to double for
error bars to be shown. Any other value, such as null or 0, will result
in no error bars being shown. Therefore, to only show, for example,
upper erros, simply pass in null or 0 for the lower errors.
To draw symmetric error bars, simply pass in the same range for
lowerErrors and upperErrors. However, note that if you do this,
the range will need to be a forward range, not an input range.
- void
scaleCenters
(double scaleFactor);
- Scale this object by a factor of scaleFactor in the X direction.
This is useful for getting it onto the same scale as another plot.
- void
scaleHeights
(double scaleFactor);
- Scale this object by a factor of scaleFactor in the Y direction.
This is useful for getting it onto the same scale as another plot.
- void
shiftCenters
(double shiftBy);
- Shift this graph by shiftBy units in the X direction.
This is useful for getting it onto the same scale as another plot.
- final @property const(double)[]
centers
();
- Get the
centers
of the bars.
- final @property const(double)[]
heights
();
- Get the
heights
of the bars.
- final @property const(double)[]
lowerErrors
();
- final @property const(double)[]
upperErrors
();
- @property Figure
toLabeledFigure
();
- The default labeling includes each center receiving its own x tick
label if there are <= 10 bars on the graph.
- enum
OutOfBounds
;
- Determine behavior for elements outside of a fixed-border histogram's bounds.
-
Throw
-
Throw
throws an exception.
-
Ignore
-
Ignore
simply skips the number.
- enum
HistType
;
- Controls whether a histogram plots counts or probability.
-
Counts
- The Y-axis should be counts.
-
Probability
- The Y-axis should be probabilities.
- class
Histogram
: dflplot.Plot;
- A class for plotting regular (equal-width) histograms.
- Color
barColor
;
- Color for the bars. Default is blue.
- final const pure nothrow @property uint
nBin
();
- The number of bins this histogram contains.
- Histogram
opCall
(R)(R nums, uint nBin);
- Factory method to instantiate this class. nums must be a forward range
with elements implicitly convertible to double. nBin specifies how many
bins the histogram should contain.
- Histogram
opCall
(R)(R nums, uint nBin, double leftLim, double rightLim, OutOfBounds outOfBoundsBehavior = OutOfBounds.Throw);
- Factory method to instantiate this class with predetermined limits.
This allows nums to be an input range instead of a forward range, since
no pass is necessary to compute the limits.
This function both obeys and permanently sets whatever bounds behavior
is specified (throwing or ignoring on out of bounds numbers). The
default behavior is to throw. Rationale: Errors should only pass
silently if explicitly silenced.
- Histogram
opCall
(I)(I nBin, double leftLim, double rightLim, OutOfBounds outOfBoundsBehavior = OutOfBounds.Throw);
- Create an empty histogram with pre-specified bounds, which will be
filled with data using the put method.
Note:
The only reason this is a template is because of bugs in
overloading non-templated functions agsinst templated functions.
- Histogram
put
(double num);
- Add a number to the histogram on the fly.
- Histogram
put
(const Histogram rhs);
- Add the contents of another Histogram to this one. The boundaries and
numbers of bins must be the same. This histogram's settings are
retained.
- void
scaleDistributionFunction
(LineGraph g);
- Assumes the LineGraph input is a plot of a PDF that this histogram is
supposed to approximate, and scales the Y axis of the LineGraph
accordingly so that both appear on the same scale.
If this Histogram is cumulative, assumes that the input LineGraph is
a CDF instead.
- @property void
boundsBehavior
(OutOfBounds behavior);
- Determine whether this object throws or ignores if it receives a number
outside its bounds via put.
- @property void
histType
(HistType newType);
- Set whether this histogram displays counts or probabilities.
- @property void
cumulative
(bool newVal);
- Determines whether this histogram is
cumulative
.
- class
FrequencyHistogram
: dflplot.Plot;
- Creates a histogram with equal frequency binning instead of equal width
binning. The scale of a
FrequencyHistogram
is the probability density scale.
Note that equal frequency binning doesn't work with discrete
distributions where probability density may be infinite at a point.
Therefore, if a probability density is calculated to be infinite, this
class will throw.
- Color
barColor
;
- The color of the bars.
- FrequencyHistogram
opCall
(R)(R nums, uint nBin);
- Create a FrequencyHistogram. R must be an input range with elements
implicitly convertible to double. nBin must be > 0 and <= nums.length.
Throws:
Exception if the density for any bin is infinite.
- class
UniqueHistogram
: dflplot.BarPlot;
- Creates a histogram in which every unique value gets its own bin.
Useful for histograms where the distribution is known to be discrete over
a small set of values.
Hint:
Since this class inherits from BarPlot, BarPlot.centers will provide
a list of the unique values found. This can be used to label the X
axis.
- immutable uint
nElem
;
- The total count of this histogram.
- UniqueHistogram
opCall
(R)(R nums, double widthFactor = 0.8);
- Create a UniqueHistogram. R must be an input range with elements
implicitly convertible to double. The width of each bin will be
widthFactor times the minimum distance between unique values. widthFactor
must be > 0 and <= 1.
- @property void
histType
(HistType newType);
- Set whether this histogram displays counts or probabilities.
- class
HeatMap
: dflplot.Plot;
- Class for drawing a heat map.
- Color
coldColor
;
- The color to use for small values.
- Color
hotColor
;
- The color to use for large values.
- HeatMap
opCall
(R)(R data);
- Create a heat map from a matrix represented as a range of ranges.
The matrix must be rectangular. The elements of the ranges must
be implicitly convertible to double.
- final @property uint
nRows
();
- final @property uint
nCols
();
- class
HeatScatter
: dflplot.HeatMap;
- Creates a heat map representing the density of a 2-d probability
distribution. This is useful when you want to visualize a joint
probability distribution but the sample size is so large that a
scatter plot would have an overwhelming number of points.
- HeatScatter
opCall
(R1, R2)(R1 x, R2 y, uint nRows = 10, uint nCols = 10);
- Create a HeatScatter. x, y must be forward ranges with elements
implicitly convertible to double, and must have the same lengths.
- HeatScatter
opCall
(R1, R2)(R1 x, R2 y, uint nRows, uint nCols, double xMin, double xMax, double yMin, double yMax, OutOfBounds boundsBehavior = OutOfBounds.Throw);
- Create a HeatScatter with pre-specified bounds. x, y must be forward
ranges with elements implicitly convertible to double, and must have the
same lengths.
- HeatScatter
opCall
(I)(I nRows, uint nCols, double xMin, double xMax, double yMin, double yMax, OutOfBounds boundsBehavior = OutOfBounds.Throw);
- Create a blank HeatScatter to fill in using the put() method.
Note:
This is a template only because templates can't be overloaded
against regular functions.
- HeatScatter
put
(double x, double y);
- Add an element to the plot.
- HeatScatter
put
(const HeatScatter rhs);
- Add another HeatScatter's data to this. The boundaries and row and
column counts must be the same. The settings from this HeatScatter are
preserved.
- @property void
boundsBehavior
(OutOfBounds behavior);
- Determine whether this object throws or ignores if it receives a number
outside its bounds via put.
- class
ScatterPlot
: dflplot.Plot;
- Class for drawing a scatter plot.
- Color
pointColor
;
- The color of a point on the scatter plot. The default is black.
- char
pointSymbol
;
- The symbol that should be used on the plot. x and o work pretty well.
The default is x.
- ScatterPlot
opCall
(R1, R2)(R1 x, R2 y);
- Factory method for creating a ScatterPlot. x and y must both be
input ranges of the same length, with elements implicitly convertible
to doubles. Note that they are copied inside the factory, so changes
to the original ranges after calling this factory will not affect the
plot.
- ScatterPlot
opCall
(R)(R y);
- Convenience factory that produces a ScatterPlot with a default X
axis numbered 1, 2, ..., N where N is the number of points. Mostly
useful for quick and dirty plots.
- class
LineGraph
: dflplot.Plot;
- Class for drawing a line graph, i.e. a set of points connected by lines.
- Color
lineColor
;
- The color of the line. The default is black.
- uint
lineWidth
;
- The width of the line. The default is 1.
- final @property void
errorWidth
(double newWidth);
- Error bar width, relative to the total width of the plot. Must be
between 0 and 1. If it's out of bounds, it will be set to the default
of 0.05. If no error bars are to be drawn, this option is ignored.
- LineGraph
opCall
(R1, R2)(R1 x, R2 y);
- Factory method for creating a LineGraph. x and y must both be
input ranges of the same length, with elements implicitly convertible
to doubles. Note that they are copied inside the factory, so changes
to the original ranges after calling this factory will not affect the
plot.
- LineGraph
opCall
(R)(R y);
- Convenience factory method that produces a LineGraph with a default
X axis numbered 1, 2, ..., N, where N is the number of data points,
and no error bars. This is mostly useful for quick and dirty plots.
- LineGraph
opCall
(R1, R2, R3, R4)(R1 x, R2 y, R3 lowerErrors, R4 upperErrors);
- Create a LineGraph with error bars. lowerErrors and upperErrors
must be input ranges with elements implicitly convertible to double for
error bars to be shown. Any other value, such as null or 0, will result
in no error bars being shown. Therefore, to only show, for example,
upper erros, simply pass in null or 0 for the lower errors.
To draw symmetric error bars, simply pass in the same range for
lowerErrors and upperErrors. However, note that if you do this,
the range will need to be a forward range, not an input range.
- void
scaleX
(double scaleFactor);
- Scale this object by a factor of scaleFactor in the X direction.
This is useful for getting it onto the same scale as another plot.
- void
scaleY
(double scaleFactor);
- Scale this object by a factor of scaleFactor in the Y direction.
This is useful for getting it onto the same scale as another plot.
- void
shiftX
(double shiftBy);
- Shift this graph by shiftBy units in the X direction.
This is useful for getting it onto the same scale as another plot.
- void
shiftY
(double shiftBy);
- Shift this graph by shiftBy units in the Y direction.
This is useful for getting it onto the same scale as another plot.
- class
ContinuousFunction
: dflplot.LineGraph;
- Plot a callable object on a range of values.
- ContinuousFunction
opCall
(C)(C callable, double lowerLim, double upperLim, uint nEvals = 1000);
- Create a ContinuousFunction. C is any callable type mapping a floating
point number to a number. lowerLim is the lower limit of the plot.
upperLim is the upper limit of the plot. nEvals is the number of
evalutations to perform. The default is 1000. More evaluations means
more accuracy but more computational intensity.
- ContinuousFunction
fromAlias
(alias callable)(double lowerLim, double upperLim, uint nEvals = 1000);
- Create a ContinuousFunction using a template alias parameter instead of
a callable object.
Note:
This function is given an name instead of opCall because DMD
thinks you're trying to instantiate a class if you do
ContinuousFunction!fun(...).
- class
DiscreteFunction
: dflplot.BarPlot;
- Plot a callable object on a range of values.
- DiscreteFunction
opCall
(C)(C callable, int lowerLim, int upperLim);
- Create a DiscreteFunction. C is any callable type mapping an integer
to a number. lowerLim is the lower limit of the plot.
upperLim is the upper limit of the plot.
- DiscreteFunction
fromAlias
(alias callable)(int lowerLim, int upperLim);
- Create a DiscreteFunction using a template alias parameter instead of
a callable object.
Note:
This function is given an name instead of opCall because DMD
thinks you're trying to instantiate a class if you do
ContinuousFunction!fun(...).
- class
RocCurve
: dflplot.LineGraph;
- Plots a ROC curve, or a curve with sensitivity on the Y-axis
and 1 - specificity on the X-axis. This is a useful metric for
determining how well a test statistic discriminates between two classes.
The following assumptions are made in this implementation:
1. For some cutoff value c and test statistic T, your decision rule is of
the form "Class A if T larger than c, Class B if T smaller than c".
2. In the case of ties, i.e. if class A and class B both have an identical
value, linear interpolation is used. This is because changing the
value of c infinitesimally will change both sensitivity and specificity
in these cases.
- RocCurve
opCall
(R1, R2)(R1 classATs, R2 classBTs);
- Create a RocCurve. classATs are the test statistics that are
"supposed" to be bigger, classBTs are the test statistics that are
"supposed to be smaller. Both R1 and R2 must be input ranges with
elements implicitly convertible to double.
- final const pure nothrow @property double
auroc
();
- Returns the area under the ROC curve.
- @property Figure
toLabeledFigure
();
- Default title is the area under the curve. Default x label is
"1 - Specificity". Default y label is "Sensitivity".
- class
QQPlot
: dflplot.ScatterPlot;
- Plots the quantiles of a set of data on the Y axis against the theoretical
qualtiles or the quantiles of another set of data on the X axis.
- Color
lineColor
;
- The color of the line that indicates identical distributions.
The default is red.
- uint
lineWidth
;
- The width of the line that indicates identical distributions.
The default is 2.
- QQPlot
opCall
(R, C)(R dataRange, C quantileFunction);
- Create a QQPlot. dataRange must be an input range with elements
implicitly convertible to doubles. quantileFunction must be a
callable (function pointer, delegate, functor, etc.) mapping any
number between 0 and 1 to its quantile.
Examples:
auto norms = randArray!rNorm(100, 0, 1);
auto theoretical = paramFunctor!invNormalCDF(0, 1);
auto fig = new Figure(
QQPlot(norms, theoretical)
);
fig.showAsMain();
- @property Figure
toLabeledFigure
();
- Default x label is "Theoretical Quantiles". Default y label is
"Empirical Quantiles".
|