Dynamically Generated Graphs With PHP
A requested feature I recently implemented was the ability to view your character’s progress in a chart. For example, you can view how quickly you’ve leveled for the past month, or see the fluctuations in the amount of cash you have in the bank.
There are several libraries for generating graphs with PHP, but I went with PHPlot. It is easy and highly customizable. Other graphing packages, such as JpGraph look like they would make more attractive graphs, but are either more complicated and/or not free for commercial use. I was only concerned with making bar graphs, but others are supported by PHPlot and most of the other packages.
Here is the end result:

And here is the PHP that generates it:
// This is to format the x values so that they decrement from left to right
function format_x_value($value, $numDays) {
return $numDays - $value;
}
// Every day at midnight, we insert a row in the table StatLog with the current
// fighting stats, money, health, and level
$query = "SELECT * FROM StatLog WHERE UserId='".$_SESSION["Id"]."' ORDER BY Date ASC";
$result = mysql_query($query);
if ($result) {
$stat = "Level";
if (isset($_GET["stat"])) {
$stat = $_GET["stat"];
if ($stat == "Potency" || $stat == "Girth" || $stat == "Resp" || $stat == "Level"
|| $stat == "MoneyBank" || $stat == "TotalHealth" || $stat == "Total") {
// no op
} else {
// not acceptable stat specified - use level by default
$stat = "Level";
}
}
// Use an array of arrays to make a bar graph with PHPlot
$data = array();
$index = 0;
$numDays = mysql_num_rows($result);
while ($row = mysql_fetch_assoc($result)) {
if ($stat == "Total") {
$data[$index] = array('', $index, $row["Potency"]+$row["Resp"]+$row["Girth"]);
} else {
$data[$index] = array('', $index, $row[$stat]);
}
$index++;
}
$plot = new PHPlot();
// Only get one x tick per record
$plot->SetNumXTicks($numDays-1);
// Use formatting function to reverse number ordering
$plot->SetXLabelType('custom', 'format_x_value', $numDays);
// Set data to use for graph
$plot->SetDataValues($data);
// Set graph's title
$plot->SetTitle($stat . " Log");
// data-data is the type for a bar graph
$plot->SetDataType('data-data');
// Set x-axis title
$plot->SetXTitle("Days Ago");
// Set y-axis title
$plot->SetYTitle($stat);
$plot->SetDrawPlotAreaBackground("true");
// Make bg transparent
$plot->SetBackgroundColor('yellow');
$plot->SetTransparentColor('yellow');
// Set plot bg color
$plot->SetPlotBgColor("DarkGreen");
$plot->DrawGraph();
} else {
echo mysql_error();
}
Then, from another page, the users can select the stat they would like a graph of and it is passed along like so:
<img src="viewgraph.php?stat=Potency" />
I’d be interested in hearing about other PHP graphing packages, but for now, I’m quite happy with these results.
