SVGGraph with responsive design

« Return to SVGGraph page

SVG is a vector-based format, so it should be easy enough to make an embedded SVG graphic resize with the browser window, or fit to a given size. It is possible, but 2.17 is the first version of SVGGraph to add support for it without having to modify the SVG output and with the Javascript elements continuing to work.

Enabling dynamic sizing with auto_fit

Version 2.17 of SVGGraph adds an option to change the attributes of the svg element to make the SVG fit into its container. This option is auto_fit, which is off (false) by default.

Setting auto_fit to true changes the SVG width and height attributes to 100% instead of the pixel values supplied in the SVGGraph constructor. The width and height are still required as they set the native size that SVGGraph uses for positioning elements inside the SVG, and is included in the SVG viewBox attribute to tell the browser the extents of the graphic. The examples on this page have been given a native width of 700 pixels and a height of 220 pixels, since the largest space for the graph is 700 pixels wide.

The example above uses an embed element with a style attribute to set the width of the graph to 100% of the width of the containing div. Try resizing your browser to see it in action.

<div>
  <embed src="svg/auto_fit.php" type="image/svg+xml" style="width: 100%">
</div>

The relevant SVGGraph settings are shown in the fragment of PHP code below. I've used a large font for the labels and tooltips because the text scales along with the rest of the SVG content, and also increased some of the spacing to make things clearer at a reduced size. The tooltip offset has been increased so that the tooltip does not end up under the cursor when the graph is scaled down.

$settings = array(
  'auto_fit' => true,
  'axis_font_size' => 24,             'axis_text_space' => 10,
  'tooltip_font_size' => 24,          'tooltip_offset' => 20,
  'crosshairs' => true,               'crosshairs_text_font_size' => 20,
);
 
$graph = new SVGGraph(700, 220, $settings);

The auto_fit option also works with the contents of the SVG embedded directly into the page with the SVGGraph Fetch function. The example below uses the same code as the one above, fetching a GroupedBarGraph instead of the StackedBarGraph used for the first example.

0.00.51.01.50246810121416182022

The PHP code for the settings and constructor are the same, but this time the SVG is rendered in the page:

<div>
<?php
echo $graph->Fetch('GroupedBarGraph', false);
echo $graph->FetchJavascript();
?>
</div>

While you can alter the colours and other attributes of the SVG content using CSS in the page, the font sizes used for text inside the SVG are relative to the SVG document and so will not be affected by any CSS rules.

« Back to top of page Error messages »