Menu

annotated_candlesticks

PHPlot Sample - Annotated Candlesticks Plot

This sample shows a candlestick plot with an extra annotation label. The label is drawn on the right side Y axis and shows the closing price of the stock on the final day. A call-back is used to place the label.

The label position is calculated as follows. Take the final closing price, $y_final. This is the world coordinate Y value. Convert this to a Y device coordinate (pixel value) $yd. For X, use the plot_area array which is passed to the callback by PHPlot. This array contains the plot area coordinates as (x1, y1, x2, y2). The value we want is x2, the X device coordinate of the right side of the plot area. Using these values ($x2, $yd) as the base point, we can position the label just right of the right side Y axis, at the Y position corresponding to the closing price on the plot.

(2015-07-30)

Reference: Discussion forum thread

The Plot:

Plot Image


The Code:

~~~~
:::php

GetDeviceXY(0, $y_final); // Allocate colors for label text, box background and border: $color_fg = imagecolorresolve($img, 255, 0, 0); // Red $color_bg = imagecolorresolve($img, 0xff, 0xff, 0xcc); // Light yellow $color_border = imagecolorresolve($img, 0, 0, 0); // Black // Get the text size, and draw an outlined box behind the text: list($text_width, $text_height) = $plot->SizeText('', 0, $y_final); $x1 = $plot_area[2] + 2; $y1 = $yd - $text_height / 2; $x2 = $x1 + $text_width + 4; $y2 = $yd + $text_height / 2 + 2; imagefilledrectangle($img, $x1, $y1, $x2, $y2, $color_bg); imagerectangle($img, $x1, $y1, $x2, $y2, $color_border); // Finally, draw the label: $plot->DrawText('', 0, $x1 + 2, $yd, $color_fg, $y_final, 'left', 'center'); } $plot = new PHPlot(600, 400); $plot->SetTitle('Demo Candlestick Plot with Annotation'); $plot->SetDataType('text-data'); $plot->SetDataValues($data); $plot->SetPlotType('candlesticks'); // Disable the Y axis 'zero magnet' : let it fit to the data. $plot->TuneYAutoRange(0); // Don't draw X ticks - with data labels they have no meaning. $plot->SetXTickPos('none'); // Place the Y axis on the right: $plot->SetYTickPos('plotright'); $plot->SetYTickLabelPos('plotright'); // And make the right margin wider, for the extra label $plot->SetMarginsPixels(NULL, 50); // Register a callback for drawing the extra label: $plot->SetCallback('draw_all', 'post_draw', array($plot, $data)); // Draw the graph: $plot->DrawGraph(); ~~~~~ ?>

Related

Discussion: Possible to create a single y-axis data label?