PHPExcel X-Axis labels missing on scatter plot - time-series
I'm attempting to create some scatter plot charts with multiple series based on a time scale and I'm having a few issues. Note that the timestamps for each series may be different hence the need to use a scatter plot.
I'll backtrack in reverse order but consider the following code:
define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '<br />');
require_once __DIR__.'/phpexcel/Classes/PHPExcel.php';
require_once __DIR__.'/phpexcel/Classes/PHPExcel/Cell/AdvancedValueBinder.php';
PHPExcel_Cell::setValueBinder( new PHPExcel_Cell_AdvancedValueBinder() );
$objPHPExcel = new PHPExcel();
$objWorksheet = $objPHPExcel->getActiveSheet();
$objWorksheet->fromArray(
array(
array('','SERIES_1','SERIES_2'),
array('2014-05-01 00:00:03',12574,''),
array('2014-05-01 04:10:01',7347,''),
array('2014-05-02 09:20:01',4175,''),
array('2014-05-03 21:30:03',1045,''),
array('2014-05-01 07:05:03','',8544),
array('2014-05-02 12:15:01','',1324),
array('2014-05-02 16:25:01','',6729),
array('2014-05-03 15:35:03','',9420),
)
);
$objWorksheet->getStyle('A2:A9')
->getNumberFormat()
->setFormatCode('yyyy-mm-dd hh:mm:ss');
// Set the Labels for each data series we want to plot
// Datatype
// Cell reference for data
// Format Code
// Number of datapoints in series
// Data values
// Data Marker
$dataseriesLabels = array(
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$B$1', NULL, 1),
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$C$1', NULL, 1),
);
// Set the X-Axis Labels
$xAxisTickValues = array(
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$A$2:$A$9', NULL, 8),
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$A$2:$A$9', NULL, 8),
);
// Set the Data values for each data series we want to plot
// Datatype
// Cell reference for data
// Format Code
// Number of datapoints in series
// Data values
// Data Marker
$dataSeriesValues = array(
new PHPExcel_Chart_DataSeriesValues('Number', 'Worksheet!$B$2:$B$9', NULL, 8),
new PHPExcel_Chart_DataSeriesValues('Number', 'Worksheet!$C$2:$C$9', NULL, 8)
);
// Build the dataseries
$series = new PHPExcel_Chart_DataSeries(
PHPExcel_Chart_DataSeries::TYPE_SCATTERCHART, // plotType
NULL, // plotGrouping (Scatter charts don't have any grouping)
range(0, count($dataSeriesValues)-1), // plotOrder
$dataseriesLabels, // plotLabel
$xAxisTickValues, // plotCategory
$dataSeriesValues, // plotValues
NULL, // smooth line
PHPExcel_Chart_DataSeries::STYLE_LINEMARKER // plotStyle
);
// Set the series in the plot area
$plotarea = new PHPExcel_Chart_PlotArea(NULL, array($series));
// Set the chart legend
$legend = new PHPExcel_Chart_Legend(PHPExcel_Chart_Legend::POSITION_RIGHT, NULL, false);
$title = new PHPExcel_Chart_Title('CHART_TITLE');
$yAxisLabel = new PHPExcel_Chart_Title('Y_AXIS_TITLE');
$xAxisLabel = new PHPExcel_Chart_Title('X_AXIS_TITLE');
// Create the chart
$chart = new PHPExcel_Chart(
'chart1', // name
$title, // title
$legend, // legend
$plotarea, // plotArea
true, // plotVisibleOnly
0, // displayBlanksAs
$xAxisLabel, // xAxisLabel
$yAxisLabel // yAxisLabel
);
// Set the position where the chart should appear in the worksheet
$chart->setTopLeftPosition('E3');
$chart->setBottomRightPosition('N18');
// Add the chart to the worksheet
$objWorksheet->addChart($chart);
// Save Excel 2007 file
echo date('H:i:s') , " Write to Excel2007 format" , EOL;
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->setIncludeCharts(TRUE);
$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
echo date('H:i:s') , " File written to " , str_replace('.php', '.xlsx', pathinfo(__FILE__, PATHINFO_BASENAME)) , EOL;
The real data will ultimately come from a database but right now I'm just trying to make things work during testing. This appears to work and while I need to do some manual formatting at the moment (remove markers, change line thickness, position axis on tick marks, change number format to yyyy-mm-dd) the graph appears to generate properly.
However if I only use one data series the graph generates properly but the x axis labels are missing. The tick marks are in the right place, only the labels are missing. As noted in the following code all I've done is comment out the second set of data.
define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '<br />');
require_once __DIR__.'/phpexcel/Classes/PHPExcel.php';
require_once __DIR__.'/phpexcel/Classes/PHPExcel/Cell/AdvancedValueBinder.php';
PHPExcel_Cell::setValueBinder( new PHPExcel_Cell_AdvancedValueBinder() );
$objPHPExcel = new PHPExcel();
$objWorksheet = $objPHPExcel->getActiveSheet();
$objWorksheet->fromArray(
array(
array('','SERIES_1','SERIES_2'),
array('2014-05-01 00:00:03',12574,''),
array('2014-05-01 04:10:01',7347,''),
array('2014-05-02 09:20:01',4175,''),
array('2014-05-03 21:30:03',1045,''),
array('2014-05-01 07:05:03','',8544),
array('2014-05-02 12:15:01','',1324),
array('2014-05-02 16:25:01','',6729),
array('2014-05-03 15:35:03','',9420),
)
);
$objWorksheet->getStyle('A2:A9')
->getNumberFormat()
->setFormatCode('yyyy-mm-dd hh:mm:ss');
// Set the Labels for each data series we want to plot
// Datatype
// Cell reference for data
// Format Code
// Number of datapoints in series
// Data values
// Data Marker
$dataseriesLabels = array(
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$B$1', NULL, 1),
// new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$C$1' NULL, 1),
);
// Set the X-Axis Labels
$xAxisTickValues = array(
new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$A$2:$A$9', NULL, 8),
// new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$A$2:$A$9', NULL, 8),
);
// Set the Data values for each data series we want to plot
// Datatype
// Cell reference for data
// Format Code
// Number of datapoints in series
// Data values
// Data Marker
$dataSeriesValues = array(
new PHPExcel_Chart_DataSeriesValues('Number', 'Worksheet!$B$2:$B$9', NULL, 8),
// new PHPExcel_Chart_DataSeriesValues('Number', 'Worksheet!$C$2:$C$9', NULL, 8)
);
// Build the dataseries
$series = new PHPExcel_Chart_DataSeries(
PHPExcel_Chart_DataSeries::TYPE_SCATTERCHART, // plotType
NULL, // plotGrouping (Scatter charts don't have any grouping)
range(0, count($dataSeriesValues)-1), // plotOrder
$dataseriesLabels, // plotLabel
$xAxisTickValues, // plotCategory
$dataSeriesValues, // plotValues
NULL, // smooth line
PHPExcel_Chart_DataSeries::STYLE_LINEMARKER // plotStyle
);
// Set the series in the plot area
$plotarea = new PHPExcel_Chart_PlotArea(NULL, array($series));
// Set the chart legend
$legend = new PHPExcel_Chart_Legend(PHPExcel_Chart_Legend::POSITION_RIGHT, NULL, false);
$title = new PHPExcel_Chart_Title('CHART_TITLE');
$yAxisLabel = new PHPExcel_Chart_Title('Y_AXIS_TITLE');
$xAxisLabel = new PHPExcel_Chart_Title('X_AXIS_TITLE');
// Create the chart
$chart = new PHPExcel_Chart(
'chart1', // name
$title, // title
$legend, // legend
$plotarea, // plotArea
true, // plotVisibleOnly
0, // displayBlanksAs
$xAxisLabel, // xAxisLabel
$yAxisLabel // yAxisLabel
);
// Set the position where the chart should appear in the worksheet
$chart->setTopLeftPosition('E3');
$chart->setBottomRightPosition('N18');
// Add the chart to the worksheet
$objWorksheet->addChart($chart);
// Save Excel 2007 file
echo date('H:i:s') , " Write to Excel2007 format" , EOL;
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->setIncludeCharts(TRUE);
$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
echo date('H:i:s') , " File written to " , str_replace('.php', '.xlsx', pathinfo(__FILE__, PATHINFO_BASENAME)) , EOL;
As mentioned above the tick marks are in the right place, only the labels are missing.
Any ideas on why the x axis labels don't show up? Also, if I create a scatter plot in Excel manually (Insert >> Chart >> Scatter) I get a time scale chart with x axis options to select minimum, maximum, major unit, and minor unit whereas the graphs from PHPExcel appear to be a category/value type since you can only select interval between tick marks and interval unit. Is there any way to change this?
Edit: Forgot to mention that I've tried using both the 1.8.0 release of PHPExcel as well as the latest develop branch on git.
Related
while using header option with XLSX.utils.json_to_sheet , headers not overriding
I'm trying to change header titles by passing an array of titles to options but it does not override the headers. Instead it inserts new headers before the original data. I am passing the same numbers of header titles. Here is my code: const ws: XLSX.WorkSheet = XLSX.utils.json_to_sheet( json, {header: headerColumns} ); const wb: XLSX.WorkBook = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(wb, ws, 'Transactions'); const excelBuffer: any = XLSX.write(wb, { bookType: 'xlsx', type: 'array' }); this.saveAsExcelFile(excelBuffer, excelFileName); And output looks like below:
The basic job of the "header" option is not to override, rather just shift the starting option of the columns. i.e. any value passed in the header option will be treated as the first column, provided the value should match with existing keys you have in the data. XLSX.utils.json_to_sheet([{A:1,B:2}, {B:2,C:3}], {header:['C']}); Here column "C" will be the first column in the excel. For more look out for detailed description here: https://docs.sheetjs.com/#sheetjs-js-xlsx
This is how I have achieved similar behavior: const XLSX = require('xlsx'); const wb = XLSX.utils.book_new(); const Heading = [ ['Sr No', 'User Name', 'Department', 'Bank', 'Country', 'Region', 'Amount'] ]; // creating sheet and adding data from 2nd row of column A. // leaving first row to add Heading const ws = XLSX.utils.json_to_sheet(data, { origin: 'A2', skipHeader: true }); // adding heading to the first row of the created sheet. // sheet already have contents from above statement. XLSX.utils.sheet_add_aoa(ws, Heading, { origin: 'A1' }); // appending sheet with a name XLSX.utils.book_append_sheet(wb, ws, 'Records'); const fileContent = XLSX.write(wb, { bookType: 'xlsx', type: 'buffer' });
Very traditional approach but working, please see complete code below: const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet( this.releaseDateWiseCountList ); worksheet.A1.v = "Pick Release Date"; worksheet.B1.v = "Task Type"; worksheet.C1.v = "First Shift"; worksheet.D1.v = "Second Shift"; worksheet.E1.v = "Total"; worksheet.F1.v = "Grand Total"; worksheet.G1.v = "Pick %"; const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] }; const excelBuffer: any = XLSX.write( workbook, { bookType: 'xlsx', type: 'array' } ); const data: Blob = new Blob([buffer], {type: EXCEL_TYPE}); FileSaver.saveAs(data, 'Result_export_' + new Date().getTime() + EXCEL_EXTENSION);
Google Calendar Orderby when using two linq queries
I am using google charts to display a stacked column chart. I am using entity framework and linq queries to gather my data from the db. The problems I am having is: that it will not order the chart. I have ordered the chart but the x-axis remains un-ordered. Can this be done through the linq query or could I do it in the script? Currently it only displays x-axis values for data that I have. Example is on the x-axis I have month number but it only displays marks for data I have eg. 1,4,5,6. Is there a way to include from 1-12 although there is no data for that particular month number? Code: #region Total Hours Per Month sick var querythpshols = (from r in db.HolidayRequestForms where (r.StartDate) >= dateAndTime group r by r.MonthOfHoliday into g select new { Value = g.Key, Count = g.Sum(h => h.HoursTaken)}); var resultthpshols = querythpshols.ToList(); var datachartthpshols = new object[resultthpshols.Count]; int G = 0; foreach (var i in resultthpshols) { datachartthpshols[G] = new object[] { i.Value.ToString(), i.Count }; G++; } string datathpshols = JsonConvert.SerializeObject(datachartthpshols, Formatting.None); ViewBag.datajthpshols = new HtmlString(datathpshols); #endregion #region Total Hours Per Month var querythpshols1 = (from r in db.HolidayRequestForms where (r.StartDate) <= dateAndTime group r by r.MonthOfHoliday into g select new { Value = g.Key, Count1 = g.Sum(r => r.HoursTaken) }) ; var resultthpshols1 = querythpshols1.ToList(); var datachartthpshols1 = new object[resultthpshols1.Count]; int P = 0; foreach (var i in resultthpshols1) { datachartthpshols1[P] = new object[] { i.Value.ToString(), i.Count1 }; P++; } string datathpshols1 = JsonConvert.SerializeObject(datachartthpshols1, Formatting.None); ViewBag.datajthpshols1 = new HtmlString(datathpshols1); #endregion Script: #*TOTAL HOURS PER MONTH CHART*# <scipt> <script> var datathpshols = '#ViewBag.datajthpshols'; var datassthpshols = JSON.parse(datathpshols); var datathpshols1 = '#ViewBag.datajthpshols1'; var datassthpshols1 = JSON.parse(datathpshols1); </script> <script type="text/javascript"> // Load the Visualization API and the corechart package. google.charts.load('current', { 'packages': ['corechart'] }); // Set a callback to run when the Google Visualization API is loaded. google.charts.setOnLoadCallback(drawChartA); // Callback that creates and populates a data table, // instantiates the pie chart, passes in the data and // draws it. function drawChartA() { // Create the data table. var data1 = new google.visualization.DataTable(); data1.addColumn('string', 'Value'); data1.addColumn('number', 'Holiday Hours Booked'); data1.addRows(datassthpshols); var data2 = new google.visualization.DataTable(); data2.addColumn('string', 'Value'); data2.addColumn('number', 'Holiday Hours Taken'); data2.addRows(datassthpshols1); var joinedData = google.visualization.data.join(data1, data2, 'full', [[0, 0]], [1], [1]); // Set chart options var options = { 'title': 'Holiday Hours Taken Per Month', 'width': 600, 'height': 350, 'hAxis': { title: 'Month Number' }, 'vAxis': { title: 'Holiday Hours Taken' }, 'is3D': true, 'isStacked': true, 'legend': 'right' }; // Instantiate and draw our chart, passing in some options. var chart = new google.visualization.ColumnChart(document.getElementById('chartTHPShols_div')); chart.draw(joinedData, options); } </script>
1) Use data table method --> sort -- to order the x-axis. joinedData.sort([{column: 0}]); 2) strings produce a discrete axis, and will only display the data available. numbers produce a continuous axis, and provide much more flexibility for the axis ticks. probably the most simplest solution would be to use a data view to convert the x-axis to numbers. (use the data view to draw the chart) var joinedData = google.visualization.data.join(data1, data2, 'full', [[0, 0]], [1], [1]); var dataView = new google.visualization.DataView(joinedData); dataView.setColumns([{ calc: function (dt, row) { return parseFloat(dt.getValue(row, 0)); }, label: joinedData.getColumnLabel(0), type: 'number' }, 1, 2]); chart.draw(dataView, options);
How do I print image on their original size in Excel using libxlsxwriter?
I just started to use libxlsxwriter to create excel sheet. My problem is I don't know how to centralized the picture and how to print pictures on their original size. Just consider the set having only 3 columns and each column having different size for example 30,10,20. I need to know what is the calculation do I need to find offset and scale values. lxw_image_options options = {.x_offset = 0, .y_offset = 0,.x_scale = 0.9, .y_scale = 0.9}; worksheet_insert_image_opt(worksheet, row, 0, img_path, &options); With that, I need to Know How many rows the picture can hold.Then only I can create the upcoming set without overlap.
how to print pictures on their original size libxlsxwriter inserts images into an xlsx file at their original size based on the width, height and DPI information in the image. It should insert images in exactly the same way as if you did it in Excel via the user interface. However, images in OpenOffice or LibreOffice may not appear to the correct size. This isn't an libxlsxwriter issue: the same thing happens with Excel. To insert images at precise positions you will need to know the dimensions of the images in pixels and also the DPI since Excel scales according to it's default DPI (usually 96) Here is an example of inserting two images in a row: /* * An example of inserting images with the libxlsxwriter library. */ #include "xlsxwriter.h" int main() { /* Create a new workbook and add a worksheet. */ lxw_workbook *workbook = workbook_new("demo.xlsx"); lxw_worksheet *worksheet = workbook_add_worksheet(workbook, NULL); lxw_image_options options = {.x_offset = 0, .y_offset = 0, .x_scale = 1, .y_scale = 1}; double default_dpi = 96.0; double image_dpi = 90.0; int32_t image_height = 138; int32_t image_offset = (int32_t)(image_height * default_dpi/image_dpi); /* Insert the first image. */ worksheet_insert_image(worksheet, 1, 2, "logo.png"); /* Insert the second image relative to the first. */ options.y_offset += image_offset; worksheet_insert_image_opt(worksheet, 1, 2, "logo.png", &options); workbook_close(workbook); return 0; } Output:
How many rows did picture hold? I want to Present my findings here to improvise the result. int row=1; lxw_image_options options = {.x_offset = 0, .y_offset = 0}; worksheet_insert_image_opt(worksheet, row, 2,"logo.png", &options); row+=(options.height/worksheet->default_row_pixels); Here I used the variable options.height to calculate How many rows the picture hold. The libxlsxwriter did read the height from the image file in pixels. It uses struct variable option only for read initialized variable it will never write anything in the set. But I did by adding the line user_options->height=options->height; in the function worksheet_insert_image_opt at worksheet.c. lxw_error worksheet_insert_image_opt(lxw_worksheet *self, lxw_row_t row_num, lxw_col_t col_num, const char *filename, lxw_image_options *user_options) { FILE *image_stream; char *short_name; lxw_image_options *options; if (!filename) { LXW_WARN("worksheet_insert_image()/_opt(): " "filename must be specified."); return LXW_ERROR_NULL_PARAMETER_IGNORED; } /* Check that the image file exists and can be opened. */ image_stream = fopen(filename, "rb"); if (!image_stream) { LXW_WARN_FORMAT1("worksheet_insert_image()/_opt(): " "file doesn't exist or can't be opened: %s.", filename); return LXW_ERROR_PARAMETER_VALIDATION; } /* Get the filename from the full path to add to the Drawing object. */ short_name = lxw_basename(filename); if (!short_name) { LXW_WARN_FORMAT1("worksheet_insert_image()/_opt(): " "couldn't get basename for file: %s.", filename); fclose(image_stream); return LXW_ERROR_PARAMETER_VALIDATION; } /* Create a new object to hold the image options. */ options = calloc(1, sizeof(lxw_image_options)); if (!options) { fclose(image_stream); return LXW_ERROR_MEMORY_MALLOC_FAILED; } if (user_options) { memcpy(options, user_options, sizeof(lxw_image_options)); options->url = lxw_strdup(user_options->url); options->tip = lxw_strdup(user_options->tip); } /* Copy other options or set defaults. */ options->filename = lxw_strdup(filename); options->short_name = lxw_strdup(short_name); options->stream = image_stream; options->row = row_num; options->col = col_num; if (!options->x_scale) options->x_scale = 1; if (!options->y_scale) options->y_scale = 1; if (_get_image_properties(options) == LXW_NO_ERROR) { user_options->height=options->height; STAILQ_INSERT_TAIL(self->image_data, options, list_pointers); return LXW_NO_ERROR; } else { free(options); return LXW_ERROR_IMAGE_DIMENSIONS; } } this how I was calcuating rows. If there is a better way please let me know.
GDAL - Warp image to inverted y-axis coordinate system (Apple MapKit) gives image upside down
I'm having an image of a map that I want to geo reference and overlay on the built-in map on iOS. I'm using GDAL programmatically. Step 1 (OK) - Geo referencing (works fine) Currently I'm calculating a GeoTransform (the 6 coefficients) from three ground control points to geo reference the image and it gives me the correct 6 coefficients. Step 2 (PROBLEM) - Warp image + get GeoTransform for new transformed image The image becomes upside down! This is because the target coordinate system (Apple's own coordinate system in MapKit) has inverted y-axis which increases as you go south. Question How can I get GDAL to warp the image correctly (and at the same time give me a correct GeoTransform to go with it)? What I've tried I changed value 5/6 in the original GeoTransform before warping. This gives a correct warp of the image, but the new GeoTransform is wrong. CURRENT CODE - (WarpResultC*)warpImageWithGeoTransform:(NSArray<NSNumber*>*)geoTransformArray sourceFile:(NSString*)inFilepath destinationFile:(NSString*)outFilepath { GDALAllRegister(); GDALDriverH hDriver; GDALDataType eDT; GDALDatasetH hDstDS; GDALDatasetH hSrcDS; // Open the source file. hSrcDS = GDALOpen( inFilepath.UTF8String, GA_ReadOnly ); CPLAssert( hSrcDS != NULL ); // Set the GeoTransform on the source image // HERE IS WHERE I NEED NEGATIVE VALUES OF 4 & 5 TO GET A PROPER IMAGE double geoTransform[] = { geoTransformArray[0].doubleValue, geoTransformArray[1].doubleValue, geoTransformArray[2].doubleValue, geoTransformArray[3].doubleValue, -geoTransformArray[4].doubleValue, -geoTransformArray[5].doubleValue }; GDALSetGeoTransform(hSrcDS, geoTransform); // Create output with same datatype as first input band. eDT = GDALGetRasterDataType(GDALGetRasterBand(hSrcDS, 1)); // Get output driver (GeoTIFF format) hDriver = GDALGetDriverByName( "GTiff" ); CPLAssert( hDriver != NULL ); // Create a transformer that maps from source pixel/line coordinates // to destination georeferenced coordinates (not destination // pixel line). We do that by omitting the destination dataset // handle (setting it to NULL). void *hTransformArg = GDALCreateGenImgProjTransformer( hSrcDS, NULL, NULL, NULL, FALSE, 0, 1 ); CPLAssert( hTransformArg != NULL ); // Get approximate output georeferenced bounds and resolution for file. double adfDstGeoTransform[6]; int nPixels=0, nLines=0; CPLErr eErr = GDALSuggestedWarpOutput( hSrcDS, GDALGenImgProjTransform, hTransformArg, adfDstGeoTransform, &nPixels, &nLines ); CPLAssert( eErr == CE_None ); GDALDestroyGenImgProjTransformer( hTransformArg ); // Create the output file. hDstDS = GDALCreate( hDriver, outFilepath.UTF8String, nPixels, nLines, 4, eDT, NULL ); CPLAssert( hDstDS != NULL ); // Write out the projection definition. GDALSetGeoTransform( hDstDS, adfDstGeoTransform ); // Copy the color table, if required. GDALColorTableH hCT = GDALGetRasterColorTable( GDALGetRasterBand(hSrcDS, 1) ); if( hCT != NULL ) GDALSetRasterColorTable( GDALGetRasterBand(hDstDS, 1), hCT ); // Setup warp options. GDALWarpOptions *psWarpOptions = GDALCreateWarpOptions(); psWarpOptions->hSrcDS = hSrcDS; psWarpOptions->hDstDS = hDstDS; /* -------------------------------------------------------------------- */ /* Do we have a source alpha band? */ /* -------------------------------------------------------------------- */ bool enableSrcAlpha = GDALGetRasterColorInterpretation( GDALGetRasterBand(hSrcDS, GDALGetRasterCount(hSrcDS) )) == GCI_AlphaBand; if(enableSrcAlpha) { printf( "Using band %d of source image as alpha.\n", GDALGetRasterCount(hSrcDS) ); } /* -------------------------------------------------------------------- */ /* Setup band mapping. */ /* -------------------------------------------------------------------- */ if(enableSrcAlpha) psWarpOptions->nBandCount = GDALGetRasterCount(hSrcDS) - 1; else psWarpOptions->nBandCount = GDALGetRasterCount(hSrcDS); psWarpOptions->panSrcBands = (int *) CPLMalloc(psWarpOptions->nBandCount*sizeof(int)); psWarpOptions->panDstBands = (int *) CPLMalloc(psWarpOptions->nBandCount*sizeof(int)); for( int i = 0; i < psWarpOptions->nBandCount; i++ ) { psWarpOptions->panSrcBands[i] = i+1; psWarpOptions->panDstBands[i] = i+1; } /* -------------------------------------------------------------------- */ /* Setup alpha bands used if any. */ /* -------------------------------------------------------------------- */ if( enableSrcAlpha ) psWarpOptions->nSrcAlphaBand = GDALGetRasterCount(hSrcDS); psWarpOptions->nDstAlphaBand = GDALGetRasterCount(hDstDS); psWarpOptions->pfnProgress = GDALTermProgress; // Establish reprojection transformer. psWarpOptions->pTransformerArg = GDALCreateGenImgProjTransformer( hSrcDS, NULL, hDstDS, NULL, FALSE, 0.0, 1 ); psWarpOptions->pfnTransformer = GDALGenImgProjTransform; // Initialize and execute the warp operation. GDALWarpOperation oOperation; oOperation.Initialize( psWarpOptions ); CPLErr warpError = oOperation.ChunkAndWarpImage( 0, 0, GDALGetRasterXSize( hDstDS ), GDALGetRasterYSize( hDstDS ) ); CPLAssert( warpError == CE_None ); GDALDestroyGenImgProjTransformer( psWarpOptions->pTransformerArg ); GDALDestroyWarpOptions( psWarpOptions ); GDALClose( hDstDS ); GDALClose( hSrcDS ); WarpResultC* warpResultC = [WarpResultC new]; warpResultC.geoTransformValues = #[#(adfDstGeoTransform[0]), #(adfDstGeoTransform[1]), #(adfDstGeoTransform[2]), #(adfDstGeoTransform[3]), #(adfDstGeoTransform[4]), #(adfDstGeoTransform[5])]; warpResultC.newX = nPixels; warpResultC.newY = nLines; return warpResultC; }
You do this by using GDALCreateGenImgProjTransformer. From documentation: Create a transformer that maps from source pixel/line coordinates to destination georeferenced coordinates (not destination pixel line). We do that by omitting the destination dataset handle (setting it to NULL). Other related info for your task from gdal_alg.h: Create image to image transformer. This function creates a transformation object that maps from pixel/line coordinates on one image to pixel/line coordinates on another image. The images may potentially be georeferenced in different coordinate systems, and may used GCPs to map between their pixel/line coordinates and georeferenced coordinates (as opposed to the default assumption that their geotransform should be used). This transformer potentially performs three concatenated transformations. The first stage is from source image pixel/line coordinates to source image georeferenced coordinates, and may be done using the geotransform, or if not defined using a polynomial model derived from GCPs. If GCPs are used this stage is accomplished using GDALGCPTransform(). The second stage is to change projections from the source coordinate system to the destination coordinate system, assuming they differ. This is accomplished internally using GDALReprojectionTransform(). The third stage is converting from destination image georeferenced coordinates to destination image coordinates. This is done using the destination image geotransform, or if not available, using a polynomial model derived from GCPs. If GCPs are used this stage is accomplished using GDALGCPTransform(). This stage is skipped if hDstDS is NULL when the transformation is created.
achartengine x-axis labels shift compared to values
I noticed that the Xlabels of my Timechart are out of sync with the X- values. The points should be right above the labels. On the left side it OK, but it shifts towards the right. I don't know how to solve this What i get: http://tinypic.com/r/2uqj905/7 How it should be like: http://www.achartengine.org/dimages/average_temperature.png I tried a line chart or converted the date to a double but that had no effect. Any help would be be nice. regards, Christian This is some of my code: XYMultipleSeriesRenderer renderer = buildRenderer(colors, styles); renderer.setPointSize(5.5f); renderer.setZoomEnabled(false, false); renderer.setMarginsColor(Color.parseColor("#00FF0000")); renderer.setAxisTitleTextSize(16); renderer.setYLabelsAlign(Align.RIGHT); renderer.setLabelsTextSize(15); renderer.setLegendTextSize(15); renderer.setMargins(new int[] { 10, 65, 18, 10 }); int length = renderer.getSeriesRendererCount(); for (int i = 0; i < length; i++) { XYSeriesRenderer seriesRenderer = (XYSeriesRenderer) renderer .getSeriesRendererAt(i); seriesRenderer.setFillPoints(true); seriesRenderer.setLineWidth(4.0f); // dikte van lijn } MinMax minMax = determineMinMax(targetSteps, samples); setChartSettings(renderer, context.getString(R.string.graph_title), dateLabelOnScreenType(type), context.getString(R.string.graph_y_axis), minMax.minX, minMax.maxX, minY, maxY, Color.WHITE, Color.BLACK); renderer.setXLabels(7); renderer.setYLabels(0); renderer.setDisplayChartValues(false); renderer.setShowGrid(true); renderer.setPanEnabled(false, false); // set the data String[] titles = new String[] { context.getString(R.string.graph_legend_target), context.getString(R.string.graph_legend_actual) }; XYMultipleSeriesDataset dataSet = buildDateDataset(titles, xSeriesList, ySeriesList); TimeChart chart = new TimeChart(dataSet, renderer); chart.setDateFormat(dateFormatOnSampleType(type)); GraphicalView gview = new GraphicalView(context, chart);
renderer.setYLabelsAlign(Align.RIGHT); Change to: renderer.setYLabelsAlign(Align.CENTER);
The solution to this was added recently. Just call: renderer.setXRoundedLabels(false)