SetSerieDescription - pChart not working - php

I'm trying to assign a label to the x axis of a Bar Chart, the label is a normal text string stored in an array under $gsettings['axisXlabel']. Unfortunatly pCharts SetSerieDescription doesn't seem to be working as expected.
Below is the function producing the graphs and an attachment of the current output. The part of interest is the 3 lines under /* Bind a data series to the X axis */
/**
* function to plot bar charts
*/
function cg_graphs_plot_bar_graph($gdata, $gsettings){
$graph_data = new pData();
if(isset($gdata['bar_plots2'])){ //if this is set, its a duel bar graph
$graph_data->addPoints($gdata['bar_plots'],"surgeondata");
$graph_data->addPoints(array(0,0,0,0),"surgeondatanull");
$graph_data->addPoints($gdata['bar_plots2'],"everyonedata");
$graph_data->addPoints(array(0,0,0,0),"everyonedatanull");
$graph_data->setSerieDrawable(array("everyonedatanull"), FALSE);
$graph_data->setSerieDescription("surgeondata",$gdata['surgeonname']);
$graph_data->setSerieDescription("everyonedata","All Surgeons");
$graph_data->setAxisUnit(0,"%");
$surgeon = array("R"=>21,"G"=>0,"B"=>0); //surgeon series colour
$all = array("R"=>191,"G"=>160,"B"=>36); //everyone series colour
$graph_data->setPalette("surgeondata",$surgeon);
$graph_data->setPalette("everyonedata",$all);
$graph_data->setPalette("surgeondatanull",$surgeon);
$graph_data->setPalette("everyonedatanull",$all);
} else {
$graph_data->addPoints($gdata['bar_plots'],"percentiles");
$graph_data->addPoints($gdata['surgeon_bar'],"surgeonbar");
$graph_data->setSerieDrawable(array("surgeonbar"), FALSE);
}
$graph_data->setAxisName(0,$gsettings['axisYlabel']);
/* Bind a data serie to the X axis */
$graph_data->addPoints($gdata['xaxis_names'],"Labels");
$graph_data->setSerieDescription("Labels",$gsettings['axisXlabel']);
$graph_data->setAbscissa("Labels");
$width=540;
$height=419;
$chart = new pImage($width,$height,$graph_data);
$chart->drawFromJPG(0,0,drupal_get_path('module', 'cg_graphs')."/images/graphbg.jpg");
/* Write the picture title */
$chart->setFontProperties(array("FontName"=>drupal_get_path('module', 'cg_graphs')."/pChart/fonts/ARIAL.TTF","FontSize"=>8));
$chart->setFontProperties(array("R"=>0,"G"=>0,"B"=>0));
$chart->drawText(270,70,$gsettings['title'],array("R"=>0,"G"=>0,"B"=>0,"Align"=>TEXT_ALIGN_MIDDLEMIDDLE, "FontSize" => 12));
/* Set the graph area */
$chart->setGraphArea(70,120,490,310);
/* Draw a rectangle */
$chart->drawFilledRectangle(70,120,489,309,array("R"=>255,"G"=>255,"B"=>255,"Dash"=>FALSE, "BorderR"=>201,"BorderG"=>201,"BorderB"=>201));
/* Turn on shadow computing */
$chart->setShadow(TRUE,array("X"=>1,"Y"=>1,"R"=>0,"G"=>0,"B"=>0,"Alpha"=>20));
$format = array(
"DisplayValues"=>FALSE,
"DisplayColor"=>DISPLAY_AUTO,
"Rounded"=>FALSE,
"Gradient"=>TRUE,
"GradientAlpha"=>100,
"GradientMode"=>GRADIENT_EFFECT_CAN,
"GradientStartR"=>251,
"GradientStartG"=>220,
"GradientStartB"=>96,
"GradientEndR"=>191,
"GradientEndG"=>160,
"GradientEndtB"=>36
);
if(isset($gdata['bar_plots2'])){
/* Draw the scale */
$chart->drawScale(array("XMargin"=>50, "Mode"=>SCALE_MODE_MANUAL, "ManualScale"=> $gsettings['maxmin'], "Pos" => SCALE_POS_LEFTRIGHT,'DrawXLines' => FALSE, 'GridTicks' => 500,'GridR'=>0,'GridG'=>0,'GridB'=>0, 'LabelRotation'=>0, 'AroundZero' => TRUE, 'Interleave' => 0.1));
$graph_data->setSerieDrawable(array("surgeondata"), FALSE);
$graph_data->setSerieDrawable(array("surgeondatanull"), TRUE);
} else {
/* Draw the scale*/
$chart->drawScale(array("XMargin"=>40, "Mode"=>SCALE_MODE_MANUAL, "ManualScale"=> $gsettings['maxmin'], "Pos" => SCALE_POS_LEFTRIGHT,'DrawXLines' => FALSE, 'GridTicks' => 500,'GridR'=>0,'GridG'=>0,'GridB'=>0, 'LabelRotation'=>0, 'AroundZero' => TRUE));
}
$chart->drawBarChart($format);
//draw next bar with new colour.
$format = array(
"DisplayValues"=>FALSE,
"DisplayColor"=>DISPLAY_AUTO,
"Rounded"=>FALSE,
"Gradient"=>TRUE,
"GradientAlpha"=>100,
"GradientMode"=>GRADIENT_EFFECT_CAN,
"GradientStartR"=>255,
"GradientStartG"=>230,
"GradientStartB"=>126,
"GradientEndR"=>21,
"GradientEndG"=>0,
"GradientEndtB"=>0
);
if(!isset($gdata['bar_plots2'])){ //not set? we need to draw the second one.
//set draw series to false / true here
$graph_data->setSerieDrawable(array("percentiles"), FALSE);
$graph_data->setSerieDrawable(array("surgeonbar"), TRUE);
$chart->drawBarChart($format);
} else {
$graph_data->setSerieDrawable(array("surgeondatanull", "everyonedata"), FALSE);
$graph_data->setSerieDrawable(array("surgeondata", "everyonedatanull"), TRUE);
$chart->drawBarChart($format);
$graph_data->setSerieDrawable(array("everyonedatanull"), FALSE);
$graph_data->setSerieDrawable(array("everyonedata"), TRUE);
$chart->drawLegend(190,100,array("Style"=>LEGEND_NOBORDER, "Mode" => LEGEND_HORIZONTAL)); //draw legand
}
$imagename = str_replace(' ', '-', $gdata['surgeonname']);
$chart->render(drupal_get_path('module', 'cg_graphs')."/pChart/examples/pictures/".$imagename."-".$gsettings['name'].".png");
}
And here's the output, I want to label the Xaxis, currently the label isn't showing. (sorry for removed title etc, data isn't in the public domain yet and names needed removing)

You need to use the function setAbscissaName as defined in http://wiki.pchart.net/doc.dataset.setabscissaname.html
Example:
$MyData->setAbscissaName("Months");
This will display Months in the X axis under ticks.

The pChart documentation is a mess. I've found an error or two where the documentation differs from the source code. Their naming scheme also needs work. It's unintuitive to anyone besides the creator.
I believe you are trying to add a label to the X-Axis. In order to do this, you need to use setXAxisName().
The "Temperature" that appears in the code for setSerieDescription() is a string that is used to tie that set of series data to that name. It is not actually the label that appears on the chart (which is the same name). It is the name that is used again in setAbscissa().

Related

Change Variable after each Rest API Call out of a list of Stock symbol names until the list is done in Wordpress?

I'm trying to use the alphavantage REST API to output stock prices through Advanced Custom Fields. My issue right now is that I don't know how I can create a list of stocksymbol names (we have specific stocks we want to check) that changes each call until all stocks have been checked.
This is my current Wordpress Code in functions.php
/* Register Stock Price Custom Post Type */
add_action('init', 'register_aktienpreise_cpt');
function register_aktienpreise_cpt(){
register_post_type('aktienpreise', [
'label' => 'Aktienpreise',
'public' => true,
'capability_type' => 'post'
]);
}
add_action( 'wp_ajax_nopriv_get_aktienpreise_from_api', 'get_aktienpreise_from_api' );
add_action( 'wp_ajax_get_aktienpreise_from_api', 'get_aktienpreise_from_api' );
/* Initialize Function */
function get_aktienpreise_from_api(){
/* Set Log File */
$file = get_stylesheet_directory() . '/report.txt';
/* Declare Current Symbol Variable and check if its not empty */
$current_symbol = ( ! empty($_POST['current_symbol']) ) ? $_POST['current_symbol'] : '';
$aktienpreise = [];
/* Results output for AlphaVantage Rest API + APIKEY - Add Current Symbol Set for each API Call */
$results = wp_remote_retrieve_body( wp_remote_get('https://www.alphavantage.co/query?function=GLOBAL_QUOTE&apikey=demo&symbol=' . $current_symbol_set ));
file_put_contents($file, "Current Symbol: " . $current_symbol. "\n\n", FILE_APPEND);
// turn it into a PHP array from JSON string
$results = json_decode( $results );
// Either the API is down or something else spooky happened. Just be done.
if( ! is_array( $results ) || empty( $results ) ){
return false;
}
/* Change Current Stock Symbol for the next call until empty */
$current_symbol = $current_symbol + $current_symbol_set;
/* Repeat Calls until results are empty */
wp_remote_post( admin_url('admin-ajax.php?action=get_aktienpreise_from_api'), [
'blocking' => false,
'sslverify' => false,
'body' => [
'current_symbol' => $current_symbol
]
] );
}
At this part
/* Change Current Stock Symbol for the next call until empty */
$current_symbol = $current_symbol + $current_symbol_set;
I'd like to have a list of specific stocks I want to check (for example Apple, IBM etc.).
The goal is that on each call the variable changes to the next stock (lets say first call Apple, second IBM), then writes those into the specific ACF Fields that I can showcase in a table on our website.
If the restapi urls would just have number increases it would be easy, but how do I do it with specific terms like "IBM" etc.
Furthermore if there are easier solutions to this please tell me so since I'm fairly new to REST APIs.
The Goal in general is to just display current stockprices of specific stocks inside a table on our website, preferably inside an ACF Field so we can do math formulas on the price (for example price x 2 for another table field).
Thanks for everyone taking their time to help me out!
Why don't you use an array for the stock symbols and do the AlphaVantage API calls inside a loop?
I will give you a quick example:
$my_symbols = [
'IBM',
'Microsoft',
'Tata'
];
foreach( $my_symbols as $current_symbol ) // iterate through the array elements
{
//... make the API calls to AlphaVantage
//... do any other business logic, like storing the API result in file or update the stocks, etc..
}
One thing to keep in mind is that you should make sure the script won't get a timeout. So increase the max_execution_time to a higher value.
Also, you don't have to call your own API here. I mean you don't have to do the wp_remote_post() to your own website.

PHPExcel Piechart legends with fix length

I have issue in setting the width of the legend lables.
I can show them but not able to show them as per expectation.
Currently it is looking like this
I want the Legend to be displayed like this
My code
//NOTE Layer for charts
$layout=new \PHPExcel_Chart_Layout();
$layout->setShowVal(true);
$layout->setShowPercent(true);
// Set series in the plot area
$pa=new \PHPExcel_Chart_PlotArea($layout, array($ds));
// Set legend
$legend=new \PHPExcel_Chart_Legend(\PHPExcel_Chart_Legend::POSITION_BOTTOM, NULL, false);
//Create Chart
$chart= new \PHPExcel_Chart('chart1',$title,$legend,$pa,true,0,NULL, NULL);
$chart->setTopLeftPosition('K'.$chart_index);
$chart->setBottomRightPosition('S'.($chart_index+20));
$ews2->addChart($chart);
I have got the solution for my problem.
I have just created array with expected label;
$pie_label = array($ea->getActiveSheet()->getCell("E".$i)->getValue(),$ea->getActiveSheet()->getCell("F".$i)->getValue(),$ea->getActiveSheet()->getCell("G".$i)->getValue(),$ea->getActiveSheet()->getCell("H".$i)->getValue());
and append it at end of the funtion of PHPExcel_Chart_DataSeriesValues,and converted my second parameter of function to null.
$spec_label = array(new \PHPExcel_Chart_DataSeriesValues('String', null, NULL, 1,$pie_label),);

How to rotate full page with tcpdf?

I am using TCPDF library to write a custom size label with background image and multiple text blocks on it.
The user when sees the preview on screen of the PDF it should show in horizontal, but for printing, I need the full page rotated -90 degrees.
How can I just rotate the whole page for printing version without having to move anything?
Basically:
In my case I've already had to use a new document format for the special sizes my document required.
So I've duplicated that format, created one for Landscape and one for Portrait.
Then based on the $preview variable, if previewing I'm rendering the normal landscape document, but if not previewing, I'm using the Portrait format and orientation and also starting the transformation and rotating everything on page.
Hope this helps someone I've found no other "quick" way to accomplish this kind of full-page rotation.
<?php
// #1 get the preview attribute from
// the form that was submitted from the user
$preview= isset($_POST['preview'])?(int)$_POST['preview']:0;
// load TCPDF for CodeIgniter as a library
$this->load->library('Pdf');
// #2 set default orientation and format
$orientation='L';
$format='MAKE-L';
// #3 if not previewing, switch orientation and format to portrait
if (!$preview) {
$orientation='P';
$format='MAKE-P';
}
// create new pdf object
// (same as doing new TCPDF(), it is just the CodeIgniter wrapper)
$pdf = new Pdf($orientation, 'mm', $format, true, 'UTF-8', false);
// remove default header/footer
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->SetMargins(0, 0, 0);
$pdf->AddPage($orientation, $format);
// #4 if not previewing, start transformation
// and rotate everything before inserting any content
if (!$preview) {
// Start Transformation
$pdf->StartTransform();
// Rotate counter-clockwise centered by (x,y)
$pdf->Rotate(-90, 70, 70); // <-- TODO: test this very well because 70 and 70 was just guessing, there is no math behind that so not sure if it will work always
}
// put your content here,
// for example set font and add a text
$pdf->SetFont('times', '', 7, '', true);
$pdf->writeHTMLCell(0, 0, 25.4, 2, 'lot number', 0, 1, 0, true, '', true);
/// end content
// #5 if not in preview mode, finish the transformation
if (!$preview) {
// Stop Transformation
$pdf->StopTransform();
}
$pdf->Output('example.pdf', 'I');
/**
* Last but very important note:
* I have added my formats in tcpdf/includes/tcpdf_static.php file.
* >> MAKE-L for Landscape
* >> MAKE-P for Portrait
*/
public static $page_formats = array(
// Make
'MAKE-L' => array( 396.850, 425.196), // = ( h 140 x w 150 ) mm
// Make
'MAKE-P' => array( 425.196, 396.850 ), // = ( h 140 x w 150 ) mm
// .. rest of formats here ../
);
The setPageFormat() method should do the job. You also can pass the parameter to the $format parameter of AddPage():
$pdf->AddPage($orientation, ['format' => $format, 'Rotate' => -90]);

TCPDF 2 columns same amount of text?

Hi I'm using tcpdf to generate a dynamic pdf for an e-zine i work for. But i have a problem, When i write the body text, I need to have the same amount of text per column and i use 2 of them. It writes my html text perfectly including images and everything, but at the end it doesn't align the text of both columns...
I'm new to tcpdf and i don't have any ideas where to start looking for a solution... any ideas how can i do this?
I'm using this function to write the text, a correction or a mockup for a solution would be greatly appreciated.
/**
* Print chapter body
* #param $file (string) name of the file containing the chapter body
* #param $mode (boolean) if true the chapter body is in HTML, otherwise in simple text.
* #public
*/
public function PartBody($text, $mode=false) {
$this->selectColumn();
// get esternal file content
$content = $text;
// set font
$this->SetFont('times', '', 9);
$this->SetTextColor(50, 50, 50);
// print content
if ($mode) {
// ------ HTML MODE ------
$this->writeHTML($content, true, false, true, false, 'J');
} else {
// ------ TEXT MODE ------
$this->Write(0, $content, '', 0, 'J', true, 0, false, true, 0);
}
$this->Ln();
}

Show a particular page in PDF using DOMPDF

I am using DOMPDF to generate a PDF file from PHP. It works very good.
But now when I click on the link that generates the PDF I want it to take me to the fifth page of the PDF (if there's content on that page). Is there a way to do this?
According to the source code posted on this page, you can use the function Cpdf.openHere:
/**
* specify where the document should open when it first starts
*/
function openHere($style, $a = 0, $b = 0, $c = 0) {
// this function will open the document at a specified page, in a specified style
// the values for style, and the required paramters are:
// 'XYZ' left, top, zoom
// 'Fit'
// 'FitH' top
// 'FitV' left
// 'FitR' left,bottom,right
// 'FitB'
// 'FitBH' top
// 'FitBV' left
$this->numObj++;
$this->o_destination($this->numObj, 'new', array('page' => $this->currentPage, 'type' => $style, 'p1' => $a, 'p2' => $b, 'p3' => $c));
$id = $this->catalogId;
$this->o_catalog($id, 'openHere', $this->numObj);
}

Categories