Moodle php code to create chart using builtin chartjs

Data Prepration


$sales = new \core\chart_series('Sales', [1000, 1170, 660, 1030]);
$expenses = new \core\chart_series('Expenses', [400, 460, 1120, 540]);
$labels = ['2004', '2005', '2006', '2007'];

Pie Chart / Donought

$chart = new \core\chart_pie();
//$chart->set_doughnut(true); // for donought chart
$chart->set_title('PIE CHART');
$chart->add_series($sales);
$chart->set_labels($labels);
echo $OUTPUT->render($chart);

Line Chart

$chart = new \core\chart_line();
//$chart->set_smooth(true);
$chart->set_title('SMOOTH LINES CHART');
$chart->add_series($sales);
$chart->add_series($expenses);
$chart->set_labels($labels);
echo $OUTPUT->render($chart);

Bar Chart

$chart = new \core\chart_bar();
$chart->set_title('BAR CHART');
// for stacked
// $chart->set_title('STACKED BAR CHART');
// $chart->set_stacked(true);
// for horizontal
// $chart->set_title('HORIZONTAL BAR CHART');
// $chart->set_horizontal(true);

$chart->add_series($sales);
$chart->add_series($expenses);
$chart->set_labels($labels);
echo $OUTPUT->render($chart);

Bar Chart with line chart

$chart = new \core\chart_bar();
$chart->set_title('BAR CHART COMBINED WITH LINE CHART');
$expensesline = new \core\chart_series('Expenses', [400, 460, 1120, 540]);
$expensesline->set_type(\core\chart_series::TYPE_LINE);
$chart->add_series($expensesline);
$chart->add_series($sales);
$chart->set_labels($labels);
echo $OUTPUT->render($chart);

Series Chart

$hills = new \core\chart_series('Hills', [700, 870, 660, 950]);
$mountain = new \core\chart_series('Mountain', [400, 460, 1350, 540]);
$sky = new \core\chart_series('Sky', [1400, 1500, 1550, 1500]);
$chart = new \core\chart_line();
$chart->set_title('AREA FILL CHART');
$chart->add_series($hills);
$chart->add_series($mountain);
$chart->add_series($sky);
$chart->set_labels($labels);
$hills->set_smooth(true);
$hills->set_fill('origin');
$mountain->set_fill('-1');
$sky->set_fill('end');
echo $OUTPUT->render($chart);

Legend Options

// hide legend
$chart->set_legend_options(['display' => false]);

// legend position
$chart->set_legend_options(['position' => 'left', 'reverse' => true]);

developerCK

E-learning Solution Architect | Technical Enthusiastic | LAMP Stack Developer | AWS Cloud Solution Architect (2x) | OCI (5X)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *