QGIS API Documentation 3.34.0-Prizren (ffbdd678812)
Loading...
Searching...
No Matches
qgsplot.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsplot.cpp
3 ---------------
4 begin : March 2022
5 copyright : (C) 2022 by Nyall Dawson
6 email : nyall dot dawson at gmail dot com
7 ***************************************************************************/
8
9/***************************************************************************
10 * *
11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the GNU General Public License as published by *
13 * the Free Software Foundation; either version 2 of the License, or *
14 * (at your option) any later version. *
15 * *
16 ***************************************************************************/
17#include "qgsplot.h"
18#include "qgslinesymbol.h"
19#include "qgsfillsymbol.h"
20#include "qgsfillsymbollayer.h"
21#include "qgslinesymbollayer.h"
22#include "qgstextrenderer.h"
24#include "qgssymbollayerutils.h"
25#include "qgsapplication.h"
28#include <functional>
29
30QgsPlot::~QgsPlot() = default;
31
32bool QgsPlot::writeXml( QDomElement &, QDomDocument &, const QgsReadWriteContext & ) const
33{
34 return true;
35}
36
37bool QgsPlot::readXml( const QDomElement &, const QgsReadWriteContext & )
38{
39 return true;
40}
41
42
43// QgsPlotAxis
44
46{
47 // setup default style
48 mNumericFormat.reset( QgsPlotDefaultSettings::axisLabelNumericFormat() );
49 mGridMinorSymbol.reset( QgsPlotDefaultSettings::axisGridMinorSymbol() );
50 mGridMajorSymbol.reset( QgsPlotDefaultSettings::axisGridMajorSymbol() );
51}
52
54
55bool QgsPlotAxis::writeXml( QDomElement &element, QDomDocument &document, const QgsReadWriteContext &context ) const
56{
57 element.setAttribute( QStringLiteral( "gridIntervalMinor" ), qgsDoubleToString( mGridIntervalMinor ) );
58 element.setAttribute( QStringLiteral( "gridIntervalMajor" ), qgsDoubleToString( mGridIntervalMajor ) );
59 element.setAttribute( QStringLiteral( "labelInterval" ), qgsDoubleToString( mLabelInterval ) );
60 element.setAttribute( QStringLiteral( "suffix" ), mLabelSuffix );
61 element.setAttribute( QStringLiteral( "suffixPlacement" ), qgsEnumValueToKey( mSuffixPlacement ) );
62
63 QDomElement numericFormatElement = document.createElement( QStringLiteral( "numericFormat" ) );
64 mNumericFormat->writeXml( numericFormatElement, document, context );
65 element.appendChild( numericFormatElement );
66
67 QDomElement gridMajorElement = document.createElement( QStringLiteral( "gridMajorSymbol" ) );
68 gridMajorElement.appendChild( QgsSymbolLayerUtils::saveSymbol( QString(), mGridMajorSymbol.get(), document, context ) );
69 element.appendChild( gridMajorElement );
70 QDomElement gridMinorElement = document.createElement( QStringLiteral( "gridMinorSymbol" ) );
71 gridMinorElement.appendChild( QgsSymbolLayerUtils::saveSymbol( QString(), mGridMinorSymbol.get(), document, context ) );
72 element.appendChild( gridMinorElement );
73
74 QDomElement textFormatElement = document.createElement( QStringLiteral( "textFormat" ) );
75 textFormatElement.appendChild( mLabelTextFormat.writeXml( document, context ) );
76 element.appendChild( textFormatElement );
77
78 return true;
79}
80
81bool QgsPlotAxis::readXml( const QDomElement &element, const QgsReadWriteContext &context )
82{
83 mGridIntervalMinor = element.attribute( QStringLiteral( "gridIntervalMinor" ) ).toDouble();
84 mGridIntervalMajor = element.attribute( QStringLiteral( "gridIntervalMajor" ) ).toDouble();
85 mLabelInterval = element.attribute( QStringLiteral( "labelInterval" ) ).toDouble();
86
87 mLabelSuffix = element.attribute( QStringLiteral( "suffix" ) );
88 mSuffixPlacement = qgsEnumKeyToValue( element.attribute( QStringLiteral( "suffixPlacement" ) ), Qgis::PlotAxisSuffixPlacement::NoLabels );
89
90 const QDomElement numericFormatElement = element.firstChildElement( QStringLiteral( "numericFormat" ) );
91 mNumericFormat.reset( QgsApplication::numericFormatRegistry()->createFromXml( numericFormatElement, context ) );
92
93 const QDomElement gridMajorElement = element.firstChildElement( QStringLiteral( "gridMajorSymbol" ) ).firstChildElement( QStringLiteral( "symbol" ) );
94 mGridMajorSymbol.reset( QgsSymbolLayerUtils::loadSymbol< QgsLineSymbol >( gridMajorElement, context ) );
95 const QDomElement gridMinorElement = element.firstChildElement( QStringLiteral( "gridMinorSymbol" ) ).firstChildElement( QStringLiteral( "symbol" ) );
96 mGridMinorSymbol.reset( QgsSymbolLayerUtils::loadSymbol< QgsLineSymbol >( gridMinorElement, context ) );
97
98 const QDomElement textFormatElement = element.firstChildElement( QStringLiteral( "textFormat" ) );
99 mLabelTextFormat.readXml( textFormatElement, context );
100
101 return true;
102}
103
105{
106 return mNumericFormat.get();
107}
108
110{
111 mNumericFormat.reset( format );
112}
113
115{
116 return mLabelSuffix;
117}
118
119void QgsPlotAxis::setLabelSuffix( const QString &suffix )
120{
121 mLabelSuffix = suffix;
122}
123
125{
126 return mSuffixPlacement;
127}
128
130{
131 mSuffixPlacement = placement;
132}
133
135{
136 return mGridMajorSymbol.get();
137}
138
140{
141 mGridMajorSymbol.reset( symbol );
142}
143
145{
146 return mGridMinorSymbol.get();
147}
148
150{
151 mGridMinorSymbol.reset( symbol );
152}
153
155{
156 return mLabelTextFormat;
157}
158
160{
161 mLabelTextFormat = format;
162}
163
164
165//
166// Qgs2DPlot
167//
168
170 : mMargins( 2, 2, 2, 2 )
171{
172 // setup default style
173 mChartBackgroundSymbol.reset( QgsPlotDefaultSettings::chartBackgroundSymbol() );
174 mChartBorderSymbol.reset( QgsPlotDefaultSettings::chartBorderSymbol() );
175}
176
177bool Qgs2DPlot::writeXml( QDomElement &element, QDomDocument &document, const QgsReadWriteContext &context ) const
178{
179 QgsPlot::writeXml( element, document, context );
180
181 element.setAttribute( QStringLiteral( "minX" ), qgsDoubleToString( mMinX ) );
182 element.setAttribute( QStringLiteral( "maxX" ), qgsDoubleToString( mMaxX ) );
183 element.setAttribute( QStringLiteral( "minY" ), qgsDoubleToString( mMinY ) );
184 element.setAttribute( QStringLiteral( "maxY" ), qgsDoubleToString( mMaxY ) );
185
186 QDomElement xAxisElement = document.createElement( QStringLiteral( "xAxis" ) );
187 mXAxis.writeXml( xAxisElement, document, context );
188 element.appendChild( xAxisElement );
189 QDomElement yAxisElement = document.createElement( QStringLiteral( "yAxis" ) );
190 mYAxis.writeXml( yAxisElement, document, context );
191 element.appendChild( yAxisElement );
192
193 QDomElement backgroundElement = document.createElement( QStringLiteral( "backgroundSymbol" ) );
194 backgroundElement.appendChild( QgsSymbolLayerUtils::saveSymbol( QString(), mChartBackgroundSymbol.get(), document, context ) );
195 element.appendChild( backgroundElement );
196 QDomElement borderElement = document.createElement( QStringLiteral( "borderSymbol" ) );
197 borderElement.appendChild( QgsSymbolLayerUtils::saveSymbol( QString(), mChartBorderSymbol.get(), document, context ) );
198 element.appendChild( borderElement );
199
200 element.setAttribute( QStringLiteral( "margins" ), mMargins.toString() );
201
202 return true;
203}
204
205bool Qgs2DPlot::readXml( const QDomElement &element, const QgsReadWriteContext &context )
206{
207 QgsPlot::readXml( element, context );
208
209 mMinX = element.attribute( QStringLiteral( "minX" ) ).toDouble();
210 mMaxX = element.attribute( QStringLiteral( "maxX" ) ).toDouble();
211 mMinY = element.attribute( QStringLiteral( "minY" ) ).toDouble();
212 mMaxY = element.attribute( QStringLiteral( "maxY" ) ).toDouble();
213
214 const QDomElement xAxisElement = element.firstChildElement( QStringLiteral( "xAxis" ) );
215 mXAxis.readXml( xAxisElement, context );
216 const QDomElement yAxisElement = element.firstChildElement( QStringLiteral( "yAxis" ) );
217 mYAxis.readXml( yAxisElement, context );
218
219 const QDomElement backgroundElement = element.firstChildElement( QStringLiteral( "backgroundSymbol" ) ).firstChildElement( QStringLiteral( "symbol" ) );
220 mChartBackgroundSymbol.reset( QgsSymbolLayerUtils::loadSymbol< QgsFillSymbol >( backgroundElement, context ) );
221 const QDomElement borderElement = element.firstChildElement( QStringLiteral( "borderSymbol" ) ).firstChildElement( QStringLiteral( "symbol" ) );
222 mChartBorderSymbol.reset( QgsSymbolLayerUtils::loadSymbol< QgsFillSymbol >( borderElement, context ) );
223
224 mMargins = QgsMargins::fromString( element.attribute( QStringLiteral( "margins" ) ) );
225
226 return true;
227}
228
230{
231 QgsExpressionContextScope *plotScope = new QgsExpressionContextScope( QStringLiteral( "plot" ) );
232 const QgsExpressionContextScopePopper scopePopper( context.expressionContext(), plotScope );
233
234 mChartBackgroundSymbol->startRender( context );
235 mChartBorderSymbol->startRender( context );
236 mXAxis.gridMinorSymbol()->startRender( context );
237 mYAxis.gridMinorSymbol()->startRender( context );
238 mXAxis.gridMajorSymbol()->startRender( context );
239 mYAxis.gridMajorSymbol()->startRender( context );
240
241 const double firstMinorXGrid = std::ceil( mMinX / mXAxis.gridIntervalMinor() ) * mXAxis.gridIntervalMinor();
242 const double firstMajorXGrid = std::ceil( mMinX / mXAxis.gridIntervalMajor() ) * mXAxis.gridIntervalMajor();
243 const double firstMinorYGrid = std::ceil( mMinY / mYAxis.gridIntervalMinor() ) * mYAxis.gridIntervalMinor();
244 const double firstMajorYGrid = std::ceil( mMinY / mYAxis.gridIntervalMajor() ) * mYAxis.gridIntervalMajor();
245 const double firstXLabel = std::ceil( mMinX / mXAxis.labelInterval() ) * mXAxis.labelInterval();
246 const double firstYLabel = std::ceil( mMinY / mYAxis.labelInterval() ) * mYAxis.labelInterval();
247
248 const QString xAxisSuffix = mXAxis.labelSuffix();
249 const QString yAxisSuffix = mYAxis.labelSuffix();
250
251 const QRectF plotArea = interiorPlotArea( context );
252
253 const double xTolerance = mXAxis.gridIntervalMinor() / 100000;
254 const double yTolerance = mYAxis.gridIntervalMinor() / 100000;
255
256 QgsNumericFormatContext numericContext;
257
258 // calculate text metrics
259 double maxYAxisLabelWidth = 0;
260 plotScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "plot_axis" ), QStringLiteral( "y" ), true ) );
261 for ( double currentY = firstYLabel; ; currentY += mYAxis.labelInterval() )
262 {
263 const bool hasMoreLabels = currentY + mYAxis.labelInterval() <= mMaxY && !qgsDoubleNear( currentY + mYAxis.labelInterval(), mMaxY, yTolerance );
264 plotScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "plot_axis_value" ), currentY, true ) );
265 QString text = mYAxis.numericFormat()->formatDouble( currentY, numericContext );
266 switch ( mYAxis.labelSuffixPlacement() )
267 {
269 break;
270
272 text += yAxisSuffix;
273 break;
274
276 if ( currentY == firstYLabel )
277 text += yAxisSuffix;
278 break;
279
281 if ( !hasMoreLabels )
282 text += yAxisSuffix;
283 break;
284
286 if ( currentY == firstYLabel || !hasMoreLabels )
287 text += yAxisSuffix;
288 break;
289 }
290
291 maxYAxisLabelWidth = std::max( maxYAxisLabelWidth, QgsTextRenderer::textWidth( context, mYAxis.textFormat(), { text } ) );
292 if ( !hasMoreLabels )
293 break;
294 }
295
296 const double chartAreaLeft = plotArea.left();
297 const double chartAreaRight = plotArea.right();
298 const double chartAreaTop = plotArea.top();
299 const double chartAreaBottom = plotArea.bottom();
300
301 // chart background
302 mChartBackgroundSymbol->renderPolygon( QPolygonF(
303 {
304 QPointF( chartAreaLeft, chartAreaTop ),
305 QPointF( chartAreaRight, chartAreaTop ),
306 QPointF( chartAreaRight, chartAreaBottom ),
307 QPointF( chartAreaLeft, chartAreaBottom ),
308 QPointF( chartAreaLeft, chartAreaTop )
309 } ), nullptr, nullptr, context );
310
311 const double xScale = ( chartAreaRight - chartAreaLeft ) / ( mMaxX - mMinX );
312 const double yScale = ( chartAreaBottom - chartAreaTop ) / ( mMaxY - mMinY );
313
314 constexpr int MAX_OBJECTS = 1000;
315
316 // grid lines
317
318 // x
319 plotScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "plot_axis" ), QStringLiteral( "x" ), true ) );
320 double nextMajorXGrid = firstMajorXGrid;
321 int objectNumber = 0;
322 for ( double currentX = firstMinorXGrid; objectNumber < MAX_OBJECTS && ( currentX <= mMaxX && !qgsDoubleNear( currentX, mMaxX, xTolerance ) ); currentX += mXAxis.gridIntervalMinor(), ++objectNumber )
323 {
324 bool isMinor = true;
325 if ( qgsDoubleNear( currentX, nextMajorXGrid, xTolerance ) )
326 {
327 isMinor = false;
328 nextMajorXGrid += mXAxis.gridIntervalMajor();
329 }
330
331 plotScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "plot_axis_value" ), currentX, true ) );
332
333 QgsLineSymbol *currentGridSymbol = isMinor ? mXAxis.gridMinorSymbol() : mXAxis.gridMajorSymbol();
334 currentGridSymbol->renderPolyline( QPolygonF(
335 QVector<QPointF>
336 {
337 QPointF( ( currentX - mMinX ) * xScale + chartAreaLeft, chartAreaBottom ),
338 QPointF( ( currentX - mMinX ) * xScale + chartAreaLeft, chartAreaTop )
339 } ), nullptr, context );
340 }
341
342 // y
343 plotScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "plot_axis" ), QStringLiteral( "y" ), true ) );
344 double nextMajorYGrid = firstMajorYGrid;
345 objectNumber = 0;
346 for ( double currentY = firstMinorYGrid; objectNumber < MAX_OBJECTS && ( currentY <= mMaxY && !qgsDoubleNear( currentY, mMaxY, yTolerance ) ); currentY += mYAxis.gridIntervalMinor(), ++objectNumber )
347 {
348 bool isMinor = true;
349 if ( qgsDoubleNear( currentY, nextMajorYGrid, yTolerance ) )
350 {
351 isMinor = false;
352 nextMajorYGrid += mYAxis.gridIntervalMajor();
353 }
354
355 plotScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "plot_axis_value" ), currentY, true ) );
356
357 QgsLineSymbol *currentGridSymbol = isMinor ? mYAxis.gridMinorSymbol() : mYAxis.gridMajorSymbol();
358 currentGridSymbol->renderPolyline( QPolygonF(
359 QVector<QPointF>
360 {
361 QPointF( chartAreaLeft, chartAreaBottom - ( currentY - mMinY ) * yScale ),
362 QPointF( chartAreaRight, chartAreaBottom - ( currentY - mMinY ) * yScale )
363 } ), nullptr, context );
364 }
365
366 // axis labels
367
368 // x
369 plotScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "plot_axis" ), QStringLiteral( "x" ), true ) );
370 objectNumber = 0;
371 for ( double currentX = firstXLabel; ; currentX += mXAxis.labelInterval(), ++objectNumber )
372 {
373 const bool hasMoreLabels = objectNumber + 1 < MAX_OBJECTS && ( currentX + mXAxis.labelInterval() <= mMaxX || qgsDoubleNear( currentX + mXAxis.labelInterval(), mMaxX, xTolerance ) );
374 plotScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "plot_axis_value" ), currentX, true ) );
375 QString text = mXAxis.numericFormat()->formatDouble( currentX, numericContext );
376 switch ( mXAxis.labelSuffixPlacement() )
377 {
379 break;
380
382 text += xAxisSuffix;
383 break;
384
386 if ( objectNumber == 0 )
387 text += xAxisSuffix;
388 break;
389
391 if ( !hasMoreLabels )
392 text += xAxisSuffix;
393 break;
394
396 if ( objectNumber == 0 || !hasMoreLabels )
397 text += xAxisSuffix;
398 break;
399 }
400
401 QgsTextRenderer::drawText( QPointF( ( currentX - mMinX ) * xScale + chartAreaLeft, mSize.height() - context.convertToPainterUnits( mMargins.bottom(), Qgis::RenderUnit::Millimeters ) ),
402 0, Qgis::TextHorizontalAlignment::Center, { text }, context, mXAxis.textFormat() );
403 if ( !hasMoreLabels )
404 break;
405 }
406
407 // y
408 plotScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "plot_axis" ), QStringLiteral( "y" ), true ) );
409 objectNumber = 0;
410 for ( double currentY = firstYLabel; ; currentY += mYAxis.labelInterval(), ++objectNumber )
411 {
412 const bool hasMoreLabels = objectNumber + 1 < MAX_OBJECTS && ( currentY + mYAxis.labelInterval() <= mMaxY || qgsDoubleNear( currentY + mYAxis.labelInterval(), mMaxY, yTolerance ) );
413 plotScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "plot_axis_value" ), currentY, true ) );
414 QString text = mYAxis.numericFormat()->formatDouble( currentY, numericContext );
415 switch ( mYAxis.labelSuffixPlacement() )
416 {
418 break;
419
421 text += yAxisSuffix;
422 break;
423
425 if ( objectNumber == 0 )
426 text += yAxisSuffix;
427 break;
428
430 if ( !hasMoreLabels )
431 text += yAxisSuffix;
432 break;
433
435 if ( objectNumber == 0 || !hasMoreLabels )
436 text += yAxisSuffix;
437 break;
438 }
439
440 const double height = QgsTextRenderer::textHeight( context, mYAxis.textFormat(), { text } );
442 maxYAxisLabelWidth + context.convertToPainterUnits( mMargins.left(), Qgis::RenderUnit::Millimeters ),
443 chartAreaBottom - ( currentY - mMinY ) * yScale + height / 2 ),
444 0, Qgis::TextHorizontalAlignment::Right, { text }, context, mYAxis.textFormat(), false );
445 if ( !hasMoreLabels )
446 break;
447 }
448
449 // give subclasses a chance to draw their content
450 renderContent( context, plotArea );
451
452 // border
453 mChartBorderSymbol->renderPolygon( QPolygonF(
454 {
455 QPointF( chartAreaLeft, chartAreaTop ),
456 QPointF( chartAreaRight, chartAreaTop ),
457 QPointF( chartAreaRight, chartAreaBottom ),
458 QPointF( chartAreaLeft, chartAreaBottom ),
459 QPointF( chartAreaLeft, chartAreaTop )
460 } ), nullptr, nullptr, context );
461
462 mChartBackgroundSymbol->stopRender( context );
463 mChartBorderSymbol->stopRender( context );
464 mXAxis.gridMinorSymbol()->stopRender( context );
465 mYAxis.gridMinorSymbol()->stopRender( context );
466 mXAxis.gridMajorSymbol()->stopRender( context );
467 mYAxis.gridMajorSymbol()->stopRender( context );
468}
469
471{
472
473}
474
475Qgs2DPlot::~Qgs2DPlot() = default;
476
477QSizeF Qgs2DPlot::size() const
478{
479 return mSize;
480}
481
482void Qgs2DPlot::setSize( QSizeF size )
483{
484 mSize = size;
485}
486
488{
489 QgsExpressionContextScope *plotScope = new QgsExpressionContextScope( QStringLiteral( "plot" ) );
490 const QgsExpressionContextScopePopper scopePopper( context.expressionContext(), plotScope );
491
492 const double firstMinorYGrid = std::ceil( mMinY / mYAxis.gridIntervalMinor() ) * mYAxis.gridIntervalMinor();
493 const double firstXLabel = std::ceil( mMinX / mXAxis.labelInterval() ) * mXAxis.labelInterval();
494
495 const QString xAxisSuffix = mXAxis.labelSuffix();
496 const QString yAxisSuffix = mYAxis.labelSuffix();
497 const double yAxisSuffixWidth = yAxisSuffix.isEmpty() ? 0 : QgsTextRenderer::textWidth( context, mYAxis.textFormat(), { yAxisSuffix } );
498
499 QgsNumericFormatContext numericContext;
500
501 const double xTolerance = mXAxis.gridIntervalMinor() / 100000;
502 const double yTolerance = mYAxis.gridIntervalMinor() / 100000;
503
504 constexpr int MAX_LABELS = 1000;
505
506 // calculate text metrics
507 int labelNumber = 0;
508 double maxXAxisLabelHeight = 0;
509 plotScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "plot_axis" ), QStringLiteral( "x" ), true ) );
510 for ( double currentX = firstXLabel; ; currentX += mXAxis.labelInterval(), labelNumber++ )
511 {
512 const bool hasMoreLabels = labelNumber + 1 < MAX_LABELS && ( currentX + mXAxis.labelInterval() <= mMaxX || qgsDoubleNear( currentX + mXAxis.labelInterval(), mMaxX, xTolerance ) );
513
514 plotScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "plot_axis_value" ), currentX, true ) );
515 QString text = mXAxis.numericFormat()->formatDouble( currentX, numericContext );
516 switch ( mXAxis.labelSuffixPlacement() )
517 {
519 break;
520
522 text += xAxisSuffix;
523 break;
524
526 if ( labelNumber == 0 )
527 text += xAxisSuffix;
528 break;
529
531 if ( !hasMoreLabels )
532 text += xAxisSuffix;
533 break;
534
536 if ( labelNumber == 0 || !hasMoreLabels )
537 text += xAxisSuffix;
538 break;
539 }
540 maxXAxisLabelHeight = std::max( maxXAxisLabelHeight, QgsTextRenderer::textHeight( context, mXAxis.textFormat(), { text } ) );
541 if ( !hasMoreLabels )
542 break;
543 }
544
545 double maxYAxisLabelWidth = 0;
546 labelNumber = 0;
547 plotScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "plot_axis" ), QStringLiteral( "y" ), true ) );
548 for ( double currentY = firstMinorYGrid; ; currentY += mYAxis.gridIntervalMinor(), labelNumber ++ )
549 {
550 const bool hasMoreLabels = labelNumber + 1 < MAX_LABELS && ( currentY + mYAxis.gridIntervalMinor() <= mMaxY || qgsDoubleNear( currentY + mYAxis.gridIntervalMinor(), mMaxY, yTolerance ) );
551 plotScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "plot_axis_value" ), currentY, true ) );
552 const QString text = mYAxis.numericFormat()->formatDouble( currentY, numericContext );
553 double thisLabelWidth = QgsTextRenderer::textWidth( context, mYAxis.textFormat(), { text } );
554 if ( yAxisSuffixWidth > 0 )
555 {
556 switch ( mYAxis.labelSuffixPlacement() )
557 {
559 break;
560
562 thisLabelWidth += yAxisSuffixWidth;
563 break;
564
566 if ( labelNumber == 0 )
567 thisLabelWidth += yAxisSuffixWidth;
568 break;
569
571 if ( !hasMoreLabels )
572 thisLabelWidth += yAxisSuffixWidth;
573 break;
574
576 if ( labelNumber == 0 || !hasMoreLabels )
577 thisLabelWidth += yAxisSuffixWidth;
578 break;
579 }
580 }
581 maxYAxisLabelWidth = std::max( maxYAxisLabelWidth, thisLabelWidth );
582 if ( !hasMoreLabels )
583 break;
584 }
585
586 const double leftTextSize = maxYAxisLabelWidth + context.convertToPainterUnits( 1, Qgis::RenderUnit::Millimeters );
587 const double rightTextSize = 0;
588 const double bottomTextSize = maxXAxisLabelHeight + context.convertToPainterUnits( 0.5, Qgis::RenderUnit::Millimeters );
589 const double topTextSize = 0;
590
591 const double leftMargin = context.convertToPainterUnits( mMargins.left(), Qgis::RenderUnit::Millimeters ) + leftTextSize;
592 const double rightMargin = context.convertToPainterUnits( mMargins.right(), Qgis::RenderUnit::Millimeters ) + rightTextSize;
593 const double topMargin = context.convertToPainterUnits( mMargins.top(), Qgis::RenderUnit::Millimeters ) + topTextSize;
594 const double bottomMargin = context.convertToPainterUnits( mMargins.bottom(), Qgis::RenderUnit::Millimeters ) + bottomTextSize;
595
596 return QRectF( leftMargin, topMargin, mSize.width() - rightMargin - leftMargin, mSize.height() - bottomMargin - topMargin );
597}
598
600{
601 if ( !mSize.isValid() )
602 return;
603
604 // aim for about 40% coverage of label text to available space
605 constexpr double IDEAL_WIDTH = 0.4;
606 constexpr double TOLERANCE = 0.04;
607 constexpr int MAX_LABELS = 1000;
608
609 const double leftMargin = context.convertToPainterUnits( mMargins.left(), Qgis::RenderUnit::Millimeters );
610 const double rightMargin = context.convertToPainterUnits( mMargins.right(), Qgis::RenderUnit::Millimeters );
611 const double topMargin = context.convertToPainterUnits( mMargins.top(), Qgis::RenderUnit::Millimeters );
612 const double bottomMargin = context.convertToPainterUnits( mMargins.bottom(), Qgis::RenderUnit::Millimeters );
613
614 const double availableWidth = mSize.width() - leftMargin - rightMargin;
615 const double availableHeight = mSize.height() - topMargin - bottomMargin;
616
617 QgsNumericFormatContext numericContext;
618
619 auto refineIntervalForAxis = [&]( double axisMinimum, double axisMaximum,
620 const std::function< double( double ) > &sizeForLabel,
621 double availableSize, double idealSizePercent, double sizeTolerancePercent,
622 double & labelInterval, double & majorInterval, double & minorInterval )
623 {
624 auto roundBase10 = []( double value )->double
625 {
626 return std::pow( 10, std::floor( std::log10( value ) ) );
627 };
628
629 // if the current interval is good enough, don't change it!
630 double totalSize = 0;
631 int initialLabelCount = 0;
632 {
633 const double firstLabelPos = std::ceil( axisMinimum / labelInterval ) * labelInterval;
634
635 for ( double currentPos = firstLabelPos; initialLabelCount <= MAX_LABELS && currentPos <= axisMaximum; currentPos += labelInterval, ++initialLabelCount )
636 {
637 totalSize += sizeForLabel( currentPos );
638 }
639 }
640
641 // we consider the current interval as "good enough" if it results in somewhere between 20-60% label text coverage over the size
642 if ( initialLabelCount >= MAX_LABELS || ( totalSize / availableSize < ( idealSizePercent - sizeTolerancePercent ) ) || ( totalSize / availableSize > ( idealSizePercent + sizeTolerancePercent ) ) )
643 {
644 // we start with trying to fit 30 labels in and then raise the interval till we're happy
645 int numberLabelsInitial = std::floor( availableSize / 30 );
646
647 double labelIntervalTest = ( axisMaximum - axisMinimum ) / numberLabelsInitial;
648 double baseValue = roundBase10( labelIntervalTest );
649 double candidate = baseValue;
650 int currentMultiplier = 1;
651
652 int numberLabels = 0;
653 while ( true )
654 {
655 const double firstLabelPosition = std::ceil( axisMinimum / candidate ) * candidate;
656 double totalSize = 0;
657 numberLabels = 0;
658 for ( double currentPos = firstLabelPosition; currentPos <= axisMaximum; currentPos += candidate )
659 {
660 totalSize += sizeForLabel( currentPos );
661 numberLabels += 1;
662
663 if ( numberLabels > MAX_LABELS ) // avoid hangs if candidate size is very small
664 break;
665 }
666
667 if ( numberLabels <= MAX_LABELS && totalSize <= availableSize * idealSizePercent )
668 break;
669
670 if ( currentMultiplier == 1 )
671 currentMultiplier = 2;
672 else if ( currentMultiplier == 2 )
673 currentMultiplier = 5;
674 else if ( currentMultiplier == 5 )
675 {
676 baseValue *= 10;
677 currentMultiplier = 1;
678 }
679
680 candidate = baseValue * currentMultiplier;
681 }
682 labelInterval = candidate;
683 if ( numberLabels < 10 )
684 {
685 minorInterval = labelInterval / 2;
686 majorInterval = minorInterval * 4;
687 }
688 else
689 {
690 minorInterval = labelInterval;
691 majorInterval = minorInterval * 5;
692 }
693 }
694 };
695
696 {
697 double labelIntervalX = mXAxis.labelInterval();
698 double majorIntervalX = mXAxis.gridIntervalMajor();
699 double minorIntervalX = mXAxis.gridIntervalMinor();
700 const QString suffixX = mXAxis.labelSuffix();
701 const double suffixWidth = !suffixX.isEmpty() ? QgsTextRenderer::textWidth( context, mXAxis.textFormat(), { suffixX } ) : 0;
702 refineIntervalForAxis( mMinX, mMaxX, [ = ]( double position ) -> double
703 {
704 const QString text = mXAxis.numericFormat()->formatDouble( position, numericContext );
705 // this isn't accurate, as we're always considering the suffix to be present... but it's too tricky to actually consider
706 // the suffix placement!
707 return QgsTextRenderer::textWidth( context, mXAxis.textFormat(), { text } ) + suffixWidth;
708 }, availableWidth,
709 IDEAL_WIDTH, TOLERANCE, labelIntervalX, majorIntervalX, minorIntervalX );
710 mXAxis.setLabelInterval( labelIntervalX );
711 mXAxis.setGridIntervalMajor( majorIntervalX );
712 mXAxis.setGridIntervalMinor( minorIntervalX );
713 }
714
715 {
716 double labelIntervalY = mYAxis.labelInterval();
717 double majorIntervalY = mYAxis.gridIntervalMajor();
718 double minorIntervalY = mYAxis.gridIntervalMinor();
719 const QString suffixY = mYAxis.labelSuffix();
720 refineIntervalForAxis( mMinY, mMaxY, [ = ]( double position ) -> double
721 {
722 const QString text = mYAxis.numericFormat()->formatDouble( position, numericContext );
723 // this isn't accurate, as we're always considering the suffix to be present... but it's too tricky to actually consider
724 // the suffix placement!
725 return QgsTextRenderer::textHeight( context, mYAxis.textFormat(), { text + suffixY } );
726 }, availableHeight,
727 IDEAL_WIDTH, TOLERANCE, labelIntervalY, majorIntervalY, minorIntervalY );
728 mYAxis.setLabelInterval( labelIntervalY );
729 mYAxis.setGridIntervalMajor( majorIntervalY );
730 mYAxis.setGridIntervalMinor( minorIntervalY );
731 }
732}
733
735{
736 return mChartBackgroundSymbol.get();
737}
738
740{
741 mChartBackgroundSymbol.reset( symbol );
742}
743
745{
746 return mChartBorderSymbol.get();
747}
748
750{
751 mChartBorderSymbol.reset( symbol );
752}
753
755{
756 return mMargins;
757}
758
759void Qgs2DPlot::setMargins( const QgsMargins &margins )
760{
761 mMargins = margins;
762}
763
764//
765// QgsPlotDefaultSettings
766//
767
772
774{
775 std::unique_ptr< QgsSimpleLineSymbolLayer > gridMajor = std::make_unique< QgsSimpleLineSymbolLayer >( QColor( 20, 20, 20, 150 ), 0.1 );
776 gridMajor->setPenCapStyle( Qt::FlatCap );
777 return new QgsLineSymbol( QgsSymbolLayerList( { gridMajor.release() } ) );
778}
779
781{
782 std::unique_ptr< QgsSimpleLineSymbolLayer > gridMinor = std::make_unique< QgsSimpleLineSymbolLayer >( QColor( 20, 20, 20, 50 ), 0.1 );
783 gridMinor->setPenCapStyle( Qt::FlatCap );
784 return new QgsLineSymbol( QgsSymbolLayerList( { gridMinor.release() } ) );
785}
786
788{
789 std::unique_ptr< QgsSimpleFillSymbolLayer > chartFill = std::make_unique< QgsSimpleFillSymbolLayer >( QColor( 255, 255, 255 ) );
790 return new QgsFillSymbol( QgsSymbolLayerList( { chartFill.release() } ) );
791}
792
794{
795 std::unique_ptr< QgsSimpleLineSymbolLayer > chartBorder = std::make_unique< QgsSimpleLineSymbolLayer >( QColor( 20, 20, 20 ), 0.1 );
796 return new QgsFillSymbol( QgsSymbolLayerList( { chartBorder.release() } ) );
797}
PlotAxisSuffixPlacement
Placement options for suffixes in the labels for axis of plots.
Definition qgis.h:2448
@ FirstAndLastLabels
Place suffix after the first and last label values only.
@ EveryLabel
Place suffix after every value label.
@ FirstLabel
Place suffix after the first label value only.
@ LastLabel
Place suffix after the last label value only.
@ NoLabels
Do not place suffixes.
@ Millimeters
Millimeters.
void calculateOptimisedIntervals(QgsRenderContext &context)
Automatically sets the grid and label intervals to optimal values for display in the given render con...
Definition qgsplot.cpp:599
bool writeXml(QDomElement &element, QDomDocument &document, const QgsReadWriteContext &context) const override
Writes the plot's properties into an XML element.
Definition qgsplot.cpp:177
void setSize(QSizeF size)
Sets the overall size of the plot (including titles and over components which sit outside the plot ar...
Definition qgsplot.cpp:482
const QgsMargins & margins() const
Returns the margins of the plot area (in millimeters)
Definition qgsplot.cpp:754
~Qgs2DPlot() override
void render(QgsRenderContext &context)
Renders the plot.
Definition qgsplot.cpp:229
void setChartBorderSymbol(QgsFillSymbol *symbol)
Sets the symbol used to render the border of the chart.
Definition qgsplot.cpp:749
Qgs2DPlot()
Constructor for Qgs2DPlot.
Definition qgsplot.cpp:169
bool readXml(const QDomElement &element, const QgsReadWriteContext &context) override
Reads the plot's properties from an XML element.
Definition qgsplot.cpp:205
QgsFillSymbol * chartBorderSymbol()
Returns the symbol used to render the border of the chart.
Definition qgsplot.cpp:744
QSizeF size() const
Returns the overall size of the plot (in millimeters) (including titles and other components which si...
Definition qgsplot.cpp:477
void setMargins(const QgsMargins &margins)
Sets the margins of the plot area (in millimeters)
Definition qgsplot.cpp:759
QRectF interiorPlotArea(QgsRenderContext &context) const
Returns the area of the plot which corresponds to the actual plot content (excluding all titles and o...
Definition qgsplot.cpp:487
void setChartBackgroundSymbol(QgsFillSymbol *symbol)
Sets the fill symbol used to render the background of the chart.
Definition qgsplot.cpp:739
virtual void renderContent(QgsRenderContext &context, const QRectF &plotArea)
Renders the plot content.
Definition qgsplot.cpp:470
QgsFillSymbol * chartBackgroundSymbol()
Returns the fill symbol used to render the background of the chart.
Definition qgsplot.cpp:734
static QgsNumericFormatRegistry * numericFormatRegistry()
Gets the registry of available numeric formats.
A numeric formatter which returns a simple text representation of a value.
RAII class to pop scope from an expression context on destruction.
Single scope for storing variables and functions for use within a QgsExpressionContext.
void addVariable(const QgsExpressionContextScope::StaticVariable &variable)
Adds a variable into the context scope.
A fill symbol type, for rendering Polygon and MultiPolygon geometries.
A line symbol type, for rendering LineString and MultiLineString geometries.
void renderPolyline(const QPolygonF &points, const QgsFeature *f, QgsRenderContext &context, int layer=-1, bool selected=false)
Renders the symbol along the line joining points, using the given render context.
The QgsMargins class defines the four margins of a rectangle.
Definition qgsmargins.h:38
double top() const
Returns the top margin.
Definition qgsmargins.h:78
static QgsMargins fromString(const QString &string)
Returns a QgsMargins object decoded from a string, or a null QgsMargins if the string could not be in...
double right() const
Returns the right margin.
Definition qgsmargins.h:84
double bottom() const
Returns the bottom margin.
Definition qgsmargins.h:90
QString toString() const
Returns the margins encoded to a string.
double left() const
Returns the left margin.
Definition qgsmargins.h:72
A context for numeric formats.
A numeric formatter allows for formatting a numeric value for display, using a variety of different f...
virtual QString formatDouble(double value, const QgsNumericFormatContext &context) const =0
Returns a formatted string representation of a numeric double value.
QgsLineSymbol * gridMinorSymbol()
Returns the line symbol used to render the minor lines in the axis grid.
Definition qgsplot.cpp:144
bool readXml(const QDomElement &element, const QgsReadWriteContext &context)
Reads the axis' properties from an XML element.
Definition qgsplot.cpp:81
void setGridMajorSymbol(QgsLineSymbol *symbol)
Sets the symbol used to render the major lines in the axis grid.
Definition qgsplot.cpp:139
double gridIntervalMinor() const
Returns the interval of minor grid lines for the axis.
Definition qgsplot.h:104
double gridIntervalMajor() const
Returns the interval of major grid lines for the axis.
Definition qgsplot.h:118
void setNumericFormat(QgsNumericFormat *format)
Sets the numeric format used for the axis labels.
Definition qgsplot.cpp:109
QgsTextFormat textFormat() const
Returns the text format used for the axis labels.
Definition qgsplot.cpp:154
void setGridIntervalMajor(double interval)
Sets the interval of major grid lines for the axis.
Definition qgsplot.h:125
void setLabelSuffixPlacement(Qgis::PlotAxisSuffixPlacement placement)
Sets the placement for the axis label suffixes.
Definition qgsplot.cpp:129
void setGridIntervalMinor(double interval)
Sets the interval of minor grid lines for the axis.
Definition qgsplot.h:111
void setLabelInterval(double interval)
Sets the interval of labels for the axis.
Definition qgsplot.h:139
double labelInterval() const
Returns the interval of labels for the axis.
Definition qgsplot.h:132
QgsLineSymbol * gridMajorSymbol()
Returns the line symbol used to render the major lines in the axis grid.
Definition qgsplot.cpp:134
void setLabelSuffix(const QString &suffix)
Sets the axis label suffix.
Definition qgsplot.cpp:119
void setTextFormat(const QgsTextFormat &format)
Sets the text format used for the axis labels.
Definition qgsplot.cpp:159
bool writeXml(QDomElement &element, QDomDocument &document, const QgsReadWriteContext &context) const
Writes the axis' properties into an XML element.
Definition qgsplot.cpp:55
void setGridMinorSymbol(QgsLineSymbol *symbol)
Sets the symbol used to render the minor lines in the axis grid.
Definition qgsplot.cpp:149
QgsNumericFormat * numericFormat() const
Returns the numeric format used for the axis labels.
Definition qgsplot.cpp:104
Qgis::PlotAxisSuffixPlacement labelSuffixPlacement() const
Returns the placement for the axis label suffixes.
Definition qgsplot.cpp:124
QString labelSuffix() const
Returns the axis label suffix, or an empty string if no label suffix is to be used.
Definition qgsplot.cpp:114
static QgsFillSymbol * chartBorderSymbol()
Returns the default fill symbol to use for the chart area border.
Definition qgsplot.cpp:793
static QgsNumericFormat * axisLabelNumericFormat()
Returns the default numeric format to use for plot axis labels.
Definition qgsplot.cpp:768
static QgsLineSymbol * axisGridMinorSymbol()
Returns the default line symbol to use for axis minor grid lines.
Definition qgsplot.cpp:780
static QgsFillSymbol * chartBackgroundSymbol()
Returns the default fill symbol to use for the chart area background fill.
Definition qgsplot.cpp:787
static QgsLineSymbol * axisGridMajorSymbol()
Returns the default line symbol to use for axis major grid lines.
Definition qgsplot.cpp:773
virtual ~QgsPlot()
virtual bool readXml(const QDomElement &element, const QgsReadWriteContext &context)
Reads the plot's properties from an XML element.
Definition qgsplot.cpp:37
virtual bool writeXml(QDomElement &element, QDomDocument &document, const QgsReadWriteContext &context) const
Writes the plot's properties into an XML element.
Definition qgsplot.cpp:32
The class is used as a container of context for various read/write operations on other objects.
Contains information about the context of a rendering operation.
double convertToPainterUnits(double size, Qgis::RenderUnit unit, const QgsMapUnitScale &scale=QgsMapUnitScale(), Qgis::RenderSubcomponentProperty property=Qgis::RenderSubcomponentProperty::Generic) const
Converts a size from the specified units to painter units (pixels).
QgsExpressionContext & expressionContext()
Gets the expression context.
static QDomElement saveSymbol(const QString &symbolName, const QgsSymbol *symbol, QDomDocument &doc, const QgsReadWriteContext &context)
Writes a symbol definition to XML.
void stopRender(QgsRenderContext &context)
Ends the rendering process.
void startRender(QgsRenderContext &context, const QgsFields &fields=QgsFields())
Begins the rendering process for the symbol.
Container for all settings relating to text rendering.
void readXml(const QDomElement &elem, const QgsReadWriteContext &context)
Read settings from a DOM element.
QDomElement writeXml(QDomDocument &doc, const QgsReadWriteContext &context) const
Write settings into a DOM element.
static double textWidth(const QgsRenderContext &context, const QgsTextFormat &format, const QStringList &textLines, QFontMetricsF *fontMetrics=nullptr)
Returns the width of a text based on a given format.
static void drawText(const QRectF &rect, double rotation, Qgis::TextHorizontalAlignment alignment, const QStringList &textLines, QgsRenderContext &context, const QgsTextFormat &format, bool drawAsOutlines=true, Qgis::TextVerticalAlignment vAlignment=Qgis::TextVerticalAlignment::Top, Qgis::TextRendererFlags flags=Qgis::TextRendererFlags(), Qgis::TextLayoutMode mode=Qgis::TextLayoutMode::Rectangle)
Draws text within a rectangle using the specified settings.
static double textHeight(const QgsRenderContext &context, const QgsTextFormat &format, const QStringList &textLines, Qgis::TextLayoutMode mode=Qgis::TextLayoutMode::Point, QFontMetricsF *fontMetrics=nullptr, Qgis::TextRendererFlags flags=Qgis::TextRendererFlags(), double maxLineWidth=0)
Returns the height of a text based on a given format.
T qgsEnumKeyToValue(const QString &key, const T &defaultValue, bool tryValueAsKey=true, bool *returnOk=nullptr)
Returns the value corresponding to the given key of an enum.
Definition qgis.h:4555
QString qgsDoubleToString(double a, int precision=17)
Returns a string representation of a double.
Definition qgis.h:4271
QString qgsEnumValueToKey(const T &value, bool *returnOk=nullptr)
Returns the value for the given key of an enum.
Definition qgis.h:4536
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference)
Definition qgis.h:4332
QList< QgsSymbolLayer * > QgsSymbolLayerList
Definition qgssymbol.h:30
Single variable definition for use within a QgsExpressionContextScope.