RGraph 系列文章(三):条状图文档

时间:2021-12-03 11:56:57
 

Bar charts documentation

  Read comments...

 

Example

<script>
    // Some data that is to be shown on the bar chart. To show a stacked or grouped chart
    // each number should be an array of further numbers instead (as below).
    var data = [280,45,133];
    
    // An example of the data used by stacked and grouped charts
    // var data = [[1,5,6], [4,5,3], [7,8,9]]

    var bar = new RGraph.Bar({
        id: 'cvs',
        data: data,
        options: {
            labels: ['Richard', 'Alex', 'Nick'],
            gutterLeft: 45,
            backgroundBarcolor1: 'white',
            backgroundBarcolor2: 'white',
            backgroundGrid: true,
            colors: ['red']
        }
    }).draw();
</script>



 

Properties属性

You can use these properties to control how the chart apears. You can set them by including them in the options section of the configuration as above.

应用这些属性来控制图表的显示。在options中设置它们。

 

Background

backgroundBarcolor1
The color of the background bars, (1 of 2).
Default: white

backgroundBarcolor2
The color of the background bars, (2 of 2).
Default: white

backgroundGrid
Whether to show the background grid or not.
Default: true

backgroundGridColor
The color of the background grid.
Default: #ddd

backgroundGridHsize
The horizontal background grid size.
Default: 40

backgroundGridVsize
The vertical background grid size.
Default: 18

backgroundGridWidth
The width that the background grid lines are. Decimals (eg 0.5) are permitted.
Default: 1

backgroundGridBorder
Determines whether a border line is drawn around the grid.
Default: true

backgroundGridHlines
Determines whether to draw the horizontal grid lines.
Default: true

backgroundGridVlines
Determines whether to draw the vertical grid lines.
Default: true

backgroundGridAutofit
Instead of specifying a pixel width/height for the background grid, you can use autofit and specify how many horizontal and vertical lines you want.
Default: true

backgroundGridAutofitNumhlines
When using autofit this allows you to specify how many horizontal grid lines you want.
Default: 5

backgroundGridAutofitNumvlines
When using autofit this allows you to specify how many vertical grid lines you want.
Default: 20

backgroundGridAutofitAlign
If you want to have your grid lines line up with the labels (both X and Y axes), you can set this to true and RGraph will attempt to make the grid lines line up. If you have a hmargin set then the alignment will be thrown out.
Default: false

backgroundGridDotted
If you want to have your background grid dashed then set this to true.
Default: false

backgroundGridDashed
If you want to have your background grid dotted then set this to true. This takes precedence over dashed lines.
Default: false

backgroundHbars
An array of information stipulating horizontal coloured bars. You can use these to indicate limits. Eg: myBar.set('hbars', [[75, 10, 'yellow'], [85, 15, 'red']]); This would give you two bars, one red and a lower yellow bar. The units correspond to your scale, and are the starting point and the height.
Default: null

backgroundImage
If you want to specify a background image to use on your chart, specify it with this property. If you use effects with a background image on your chart it may make the effect flicker. Using a background image with the ondraw event may mean that the event fires twice. There is a property that you can check though that is set when the image has loaded: obj.__rgraph_background_image_loaded__ Simply check this flag in your ondraw event. If it's true then the background image has loaded.
Default: null

backgroundImageStretch
By default your background image is stretched (if necessary) to cover the whole chart area (gutters not included). If this is not what you want then set this property to false.
Default: true

backgroundImageX
The X position of the image. The coordinates are the top left corner of the image.
Default: null

backgroundImageY
The Y position of the image. The coordinates are the top left corner of the image.
Default: null

backgroundImageW
The width of the image. If you have a large canvas with many charts - you may need to specify this.
Default: null

backgroundImageH
The height of the image. If you have a large canvas with many charts - you may need to specify this.
Default: null

backgroundImageAlign
Instead of specifying the coordinates of the image, you can instead simply align it top, bottom, left or right. Examples are:
  • top left
  • bottom right
  • bottom
  • right

Default: null

backgroundImageAlpha
The alpha value (the opacity) of the image.
Default: 1

backgroundColor
If you want to have a single background color for your chart you can use this. It doesn't cover the gutters. If you want that then you can simply apply a CSS background color to the canvas tag.
Default: null

 

Axes properties

noaxes
Turns off the drawing of the axes
Default: false (the axes ARE drawn)

noxaxis
Whether the X axis is drawn
Default: false (the X axis IS drawn)

noyaxis
Whether the Y axis is drawn
Default: false (the Y axis IS drawn)

noendxtick
When you're combining the Bar and Line charts, you may want to use this property to stop the end X tick from being drawn.
Default: false (the end tick IS drawn)

numxticks
This controls the number of X tickmarks on the X axis.
Default: null

numyticks
The number of Y tickmarks.
Default: 10

axisColor
The color of the axes.
Default: black

axisLinewidth
The linewidth of the axes.
Default: 1

 

Colors

strokestyle
The color of the outline of the bars.
Default: rgba(0,0,0,0)

colors
An array of the colors of the bars.
Default: An array - ['rgb(0,0,255)', '#0f0', '#00f', '#ff0', '#0ff', '#0f0']

colorsSequential
If true, for regular bar charts, (not stacked or grouped), the colors that you specify will be used in a sequential fashion.
Default: false

colorsReverse
If true, for stacked bar charts only, the colors that you specify will be used in a reverse order to what they are normally.
Default: false

 

Margins

hmargin
The horizontal margin (in pixels) of the chart. The horizontal margin is on the inside of the axes.
Default: 5

hmarginGrouped
In a grouped bar chart this is the margin between bars that are on the same group. You can see examples of the hmargins in the RGraph demos.
Default: 1

gutterLeft
The left gutter of the chart, (the gutter is where the labels and title are)).
Default: 25

gutterRight
The right gutter of the chart, (the gutter is where the labels and title are).
Default: 25

gutterTop
The top gutter of the chart, (the gutter is where the labels and title are).
Default: 25

gutterBottom
The bottom gutter of the chart, (the gutter is where the labels and title are).
Default: 25

 

Labels and text

textAccessible
A new feature in 2016 that allows you to use DOM text in place of canvas text. It makes for much higher quality text that you can also select if desired (for copy/paste operations). It won't fit all situations and you can read more about the DOM text feature here. A good way to control borders/margins/padding etc is not to set them on the canvas but to wrap the canvas in a div and set them on that like this:
<div style="margin-left: 50px; display: inline-block">
    <canvas id="cvs" width="650" height="250"></canvas>
</div>

Default: true

textAccessibleOverflow
This can be visible or hidden and it controls whether the text is clipped to the edges of the canvas. It defaults to be visible and means you can set small gutters if you wish.
Default: visible

textAccessiblePointerevents
This controls whether the DOM text responds to mouse based events or not (it sets the pointer-events CSS property to none).
Default: true

textColor
The color of the labels.
Default: black

textSize
The size (in points) of the labels.
Default: 10

textAngle
The angle of the horizontal text labels (at the bottom of the chart). This can be from 90 to -90 degrees
Default: 0 (Horizontal)

textFont
The font used to render the text.
Default: Arial

labels
An array of the labels to be used on the chart.
Default: An empty array

labelsBold
Whether the labels are bold or not
Default: false

labelsColor
The color of the labels
Default: null (same as textColor)

labelsAbove
If true, values will be shown above the bars. For regular and stacked bar charts units are included, whereas for grouped bar charts they're not (usually there isn't enough space for them).
Default: false

labelsAboveDecimals
This stipulates how many decimals are used in the above bar labels.
Default: 0

labelsAboveUnitsPre
The units to put on the above labels. These are positioned BEFORE the number
Default: 0

labelsAboveUnitsPost
The units to put on the above labels. These are positioned AFTER the number
Default: 0

labelsAboveSize
The font size of the above bar labels. Useful if you only have a few bars.
Default: null

labelsAboveBackground
The background-color of the labels above the bars
Default: rgba(0,0,0,0)

labelsAboveColor
The color of the labels above the bars
Default: null(defaults to text.color setting)

labelsAboveOffset
The distance of the labels above the bars (in pixels)
Default: 4

labelsAboveAngle
You can use this to angle the text shown above the bars. It can be anything from -90 to 90 (degrees).
Default: null

labelsAboveSpecific
If instead of the values you want to show arbitrary text - you can with this. It should be an arry of the labels to be shown.
Default: null

labelsIngraph
An array of labels for the chart which are drawn "inside" the chart. If you have 5 data points then this should have a corresponding number of elements, though there is a shorthand available.
Default: null

labelsOffsetx
This allows you finer grained control in the horizontal direction over the X label positioning if you need it.
Default: 0

labelsOffsety
This allows you finer grained control in the vertical direction over the X label positioning if you need it.
Default: 0

ylabels
Can be true or false and determines whether the chart has Y axis labels.
Default: true

ylabelsCount
A value that controls how many Y labels there are. This value could formerly be either 1/3/5/10 however now it can be any number.
Default: 5

ylabelsSpecific
You can use this option to give your own Y labels (eg ['Low', 'Medium', 'High']. Note: Since March 2013 you may now need to add an extra (optionally) empty element to the array of labels to achieve your desired result.
Default: null

ylabelsOffsetx
This allows you finer grained control in the horizontal direction over the Y label positioning if you need it.
Default: 0

ylabelsOffsety
This allows you finer grained control in the vertical direction over the Y label positioning if you need it.
Default: 0

 

Titles

title
The title of the chart, if any.
Default: null

titleFont
The font that the title is rendered in. If not specified the text.font setting is used (usually Arial)
Default: null

titleSize
The size of the title. If not specified the size is usually 2pt bigger than the text.size setting.
Default: null

titleBold
Whether the title is bold or not.
Default: true

titleItalic
Whether the title is italic or not.
Default: false

titleBackground
The background color (if any) for the title.
Default: null

titleColor
The color of the title.
Default: black

titleX
To give the exact X coordinate for the title - use this
Default: null

titleY
To give the exact Y coordinate for the title - use this
Default: null

titleXaxis
This allows to specify a title for the X axis.
Default: none

titleXaxisSize
This allows you to specify a size for the X axis title.
Default: null

titleXaxisFont
This allows to specify a font for the X axis title.
Default: null

titleXaxisBold
This controls whether the X axis title is bold or not.
Default: true

titleXaxisColor
This controls the color of the X axis title.
Default: black

titleXaxisX
By giving this you can specifically set the X position of the X axis title
Default: null

titleXaxisY
By giving this you can specifically set the Y position of the X axis title
Default: null

titleYaxis
This allows to specify a title for the Y axis.
Default: none

titleYaxisSize
This allows you to specify a size for the Y axis title.
Default: null

titleYaxisFont
This allows to specify a font for the Y axis title.
Default: null

titleYaxisBold
This controls whether the Y axis title is bold or not.
Default: true

titleYaxisColor
This controls what color the Y axis is.
Default: black

titleXaxisPos
This is multiplied with the gutter to give the position of the X axis title.
Default: 0.25

titleYaxisPos
This is multiplied with the gutter to give the position of the Y axis title.
Default: 0.25

titleYaxisX
By giving this you can specifically set the X position of the Y axis title
Default: null

titleYaxisY
By giving this you can specifically set the Y position of the Y axis title
Default: null

 

Shadow

shadow
Whether a drop shadow is applied.
Default: false

shadowColor
The color of the shadow.
Default: #aaa

shadowOffsetx
The X offset of the shadow.
Default: 0

shadowOffsety
The Y offset of the shadow.
Default: 0

shadowBlur
The severity of the shadow blurring effect.
Default: 15

 

Scale

scaleFormatter
To allow thoroughly custom formats of numbers in the scale, you can use this option to specify a function that is used by RGraph to format numbers. This function should handle ALL of the formatting. Eg:

function myFormatter(obj, num)
{
    return num + 'F'; // An example of formatting
}
myGraph.set('scale.formatter', myFormatter);

Default: null

scaleRound
Whether to round the scale up. eg A maximum value of 59 results in scale to 100.
Default: false

scaleDecimals
The number of decimal places to display for the Y scale.
Default: 0

scalePoint
The character used as the decimal point.
Default: .

scaleThousand
The character used as the thousand separator
Default: ,

scaleZerostart
Whether the scale starts at zero or not.
Default: true

unitsPre
The units that the Y axis is measured in. This string is displayed BEFORE the actual number, allowing you to specify values such as "$50".
Default: none

unitsPost
The units that the Y axis is measured in. This string is displayed AFTER the actual number, allowing you to specify values such as "50ms".
Default: none

ymax
The optional maximum Y scale value. If not specified then it will be calculated.
Default: null (It's calculated)

ymin
The optional minimum Y scale value. If not specified then it will be 0.
Default: 0

 

Key

The key properties are documented on the key documentation page.

 

Interactive features

contextmenu
An array of context menu items. More information on context menus is here.
Default: [] (An empty array)

tooltips
A numerically indexed array of tooltips that are shown when a bar is clicked. These can contain HTML.
Default: null

tooltipsEffect
The effect used for showing tooltips. Can be either fade or none.
Default: fade

tooltipsEvent
This is the event that triggers the tooltips. It can be either onclick or onmousemove.
Default: onclick

tooltipsCssClass
This is the name of the CSS class the chart uses.
Default: RGraph_tooltip

tooltipsOverride
If you wish to handle showing tooltips yourself, this should be a function object which does just that. There's more information on the tooltips documentation page
Default: null

tooltipsHighlight
Set this to false if you don't want your charts to be highlighted.
Default: true

tooltipsNohideonclear
Not an option that you'll need particularly often if at all. Setting this to true means that when you call the RGraph.clear() API function tooltip DO NOT get hidden.
Default: false

tooltipsHotspotXonly
If set to true the hotspot for the tooltips will ignore the height of the bar and extend from top gutter down to the bottom gutter. This can be useful when you have zero value bars but still want to see the tooltips.
Default: false

crosshairs
If true, you will get a crosshair centering on the current mouse position.
Default: false

crosshairsLinewidth
This controls the linewidth of the crosshairs.
Default: 1

crosshairsColor
The color of the crosshairs.
Default: #333

crosshairsHlines
This determines whether the horizontal crosshair is shown.
Default: true

crosshairsVlines
This determines whether the vertical crosshair is shown.
Default: true

annotatable
Whether annotations are enabled for the chart (ie you can draw on the chart interactively.
Default: false

annotateColor
If you do not allow the use of the palette, then this will be the only colour allowed for annotations.
Default: black

annotateLinewidth
This is the line width of the annotations.
Default: 1

resizable
Defaulting to false, this determines whether your chart will be resizable. Because of the numerous event handlers this has to install code on, This feature is unlikely to work with other dynamic features (the context menu is fine however).
Default: false

resizeHandleBackground
With this you can specify the background color for the resize handle. If you're adjusting the position of the handle then you may need this to make the handle stand out more.
Default: null

resizableMaxwidth
This allows you to set a maximum width that the chart can be resized to.
Default: null

resizableMaxheight
This allows you to set a maximum height that the chart can be resized to.
Default: null

adjustable
Defaulting to false, this determines whether your bar chart will be adjustable.
Default: false

adjustableOnly
This should be an array of values that determine whether a Bar is adjustable or not. A truthy value for when it is, a falsey value for when its not.
Default: null

 

Zoom

zoomFactor
This is the factor that the chart will be zoomed by (bigger values means more zoom)
Default: 1.5

zoomFadeIn
Whether the zoomed canvas fades in or not. This also can be used to control the fade in for the zoom in thumbnail mode.
Default: true

zoomFadeOut
Whether the zoomed canvas fades out or not. This also can be used to control the fade in for the zoom in thumbnail mode.
Default: true

zoomHdir
The horizontal direction of the zoom. Possible values are: left, center, right
Default: right


zoomVdir
The vertical direction of the zoom. Possible values are: up, center, down
Default: down


zoomDelay
The delay (in milliseconds) between frames.
Default: 50

zoomFrames
The number of frames in the zoom animation.
Default: 10

zoomShadow
Whether or not the zoomed canvas has a shadow or not.
Default: true

 

Events

eventsClick
If you want to add your own onclick function you can do so by assigning it to this property. See here for details.
Default: null

eventsMousemove
If you want to add your own onmousemove function you can do so by assigning it to this property. See here for details.
Default: null

eventsMouseover
If you want to add your own onmouseover function you can do so by assigning it to this property. See here for details.
Default: null

eventsMouseout
If you want to add your own onmouseout function you can do so by assigning it to this property. See here for details.
Default: null

 

Miscellaneous

highlightStyle
By default this is null but you can set it to a function if you wish so that function is called to do the chart highlighting. Its passed the shape object as an argument.
Default: null

highlightStroke
If you use tooltips, this controls the colour of the highlight stroke.
Default: black

highlightFill
If you use tooltips, this controls the colour of the highlight fill.
Default: rgba(255,255,255,0.5)

variant
This stipulates whether you want a regular bar chart or a 3D chart. In August 2015 the 3D variant has much improved perspective. Possible values are:
  • bar
  • 3d

Default: bar

variantThreedOffsetx
This determines the size of the offset in the X direction
Default: 10

variantThreedOffsety
This determines the size of the offset in the Y direction
Default: 5

variantThreedXaxis
This allows you to turn on/off the threed X axis
Default: true

variantThreedYaxis
This allows you to turn on/off the threed Y axis
Default: true

xaxispos
The position of the X axis. This can be bottom, center or top.
Default: bottom

yaxispos
Specifies the Y axis position. Can be left or right
Default: left


grouping
How the bars are grouped, and it should be one of: grouped or stacked
Default: grouped

bevel
If true the bars will be given a 3D bevelled appearance.
Default: false

clearto
This is used in animations and effects as the default color to use when clearing the canvas.
Default: null

errorbars
This should be an array of errorbar information or it can simply be a number instead ( see below).
Default: false

errorbarsLinewidth
This is the linewidth of the errorbars.
Default: 1

errorbarsColor
This is the color of the errorbars. You can also override the color in the errorbar array.
Default: black

errorbarsCapped
This dictates whether the errorbars have caps on their ends or not.
Default: true

errorbarsCappedWidth
This is the width of the caps (in total) on the end of the errorbar.
Default: 14

combinedchartEffect
Set this to the name of an effect (eg grow ) and the CombinedChart object will use that effect to draw the chart instead of the regular draw() function
Default: null

combinedchartEffectOptions
This should be a STRING that contains a JavaScript object of options for the effect function like this:
combinedchartEffectOptions: '{frames: 300}'
It has to be a string because of a quirk of the option parsing system.
Default: null

combinedchartEffectCallback
A function that runs when this objects effect has conpleted.
Default: null

 

Methods

 

obj.get(name)
An accessor that you can use to retrieve the value of properties.

 

obj.set(name, value)
An accessor that you can use to set the value of properties.

 

obj.getShape(event)

This method makes it easier to get hold of which bar has been clicked on, or hovered over. It returns an array of:
  • The chart object
  • The X coordinate
  • The Y coordinate
  • The width of the bar
  • The height of the bar
  • The numerical index of the bar. This corresponds (for example) to the tooltips array, and the coordinates array

The shape also includes textual indexes like this: shape['object'] And they are:

  • object
  • x
  • y
  • width
  • height
  • tooltip
  • index
An example usage is:
<canvas id="cvs" width="600" height="250">[No canvas support]</canvas>

<script src="RGraph.common.core.js"></script>
<script src="RGraph.bar.js"></script>

<script>
    bar = new RGraph.Bar({
        id: 'cvs',
        data: [1.2, 1.3, 1.4, 1.5,6,1.9,2,2.1,2.5],
        options: {
            labels: ['John', 'Barry', 'Rich', 'Craig', 'Tom', 'Frank', 'Helen', 'Joyce', 'Fred']
        }
    }).draw();
    
    bar.canvas.onclick = function (e)
    {
        RGraph.Redraw();
    
        var ca  = e.target;
        var co  = ca.getContext('2d');
        var obj = ca.__object__;
        var coords  = obj.getShape(e);
        
        if (coords) {
            var top    = coords[1];
            var left   = coords[2];
            var width  = coords[3];
            var height = coords[4];
            
            co.strokeStyle = 'black';
            co.fillStyle = 'rgba(255,255,255,0.5)';
            co.strokeRect(top, left, width, height);
            co.fillRect(top, left, width, height);
        }
    }
</script>

 

obj.getShapeByX(event)

This method is similar to the above, but only uses the X coordinate to get the relevant bar.

 

obj.getValue(mixed)

This method can be used to get the value at a particular point or at the mouse coordinates, based on the scale that is in use. Not simply the coordinates of the mouse. The argument can either be an event object (for use in event listener functions) OR a two element array consisting of the X and Y coordinates (ie when you're not necessarily in an event listener). It returns null if the mouse or coordinates are in the gutter areas. An example:

bar.canvas.onclick = function (e)
{
    var obj   = e.target.__object__;
    var value = obj.getValue(e);
    
    // ...
}

 

obj.getYCoord(value)

This method can be used to get an appropriate Y coord for a value when you're doing custom drawing on the chart. It returns null if the value is out of range.

 

obj.on(event, func)

This method can be used to set an event listener on an object. It operates in a similar way to the jQuery .on() function - the first argument is the event you wish to attach to and the second is the handler function. For example:

.on('draw', function (obj)
{
    // Put event code here
});

 

The exec option and method

The exec function is documented here.

 

Errorbars

Errorbars can allow you show an upper and lower range for a particular bar likethis example page here shows. You can specify errorbars like this:

var bar = new RGraph.Bar({
    id: 'cvs',
    data: [12,18,10,9,6,20,18],
    options: {
        labels: ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'],
        shadow: false,
        colors: ['red'],
        strokestyle: 'rgba(0,0,0,0)',
        errorbars: [ [5,3], [2,6], [5,15,'blue',5,45] ],
        errorbarsLinewidth: 2,   // The default linewidth
        errorbarsColor: 'gray',  // The default color
        errorbarsCapped: true,   // Whether the ends of the errorbar have terminating lines
        errorbarsCappedWidth: 14 // The default width of the caps
    }                
}).draw();

This would give you three errorbars and the elements of each errorbar array are (each one is optional):

  • The upper extent of the errorbar
  • The lower extent of the errorbar
  • The color of this errorbar
  • The linewidth of this errorbar
  • The (total) width of the cap at the end of this errorbar

 

Note about the data_arr array

Sometimes you may wish to view your data as one big array, instead of one array per dataset. In this case the obj.data_arr is available. This is one long array containing all of the individual data points.

 

Animation Effects

These effects are available and can be used instead of the .draw() function. There are also generic effects available which you can see here: Generic effects and transitions
<script>
    /**
    * Optional callback function that's called when the effect is complete
    */
    function myCallback (obj)
    {
        // ...
    }

    var obj = new RGraph.Bar({
        id: 'cvs',
        data: [3,4,7,5,6,9,8],
        options: {
            gutterLeft: 35,
            hmargin: 60
        }
    }).wave({frames: 60}, myCallback);
    // .grow({frames: 60}, myCallback);
</script>
Share RGraph...
RGraph 系列文章(三):条状图文档 X

Comments