Reputation: 6230
In matlab/octave I can set axis equal to get a correct aspect ratio. Matplotlib has axis('equal'). How can I achieve this in with QtCharts?
Here is some example code written for octave/matlab together with the result, showing what I am trying to achieve:
x=linspace(0, 10);
plot(x, log(x));
ylim([-3 3]);
xlim([0 10]);
I have now set the axes ranges to suite the plot.
After that I do
axis equal
It has now computed a suitable range for both x and y, but the aspect ratio is wrong. You can see that it is slightly stretched in the vertical direction, by looking at the tangent at x = 1, which should form a 45 degree angle relative to the x axis since d/dx (ln(x))
evaluated at x = 1 equals 1. Doing the following adjusts the size of the plot
Notice that the range of the axes did not change. Instead, the view window is updated with the constraint that a 45 degree line in the plot is drawn as a 45 degree line on the screen. To summarize: the axes range is a hard constraint, that the view window needs to adapt to.
Upvotes: 0
Views: 148
Reputation: 91
include <QtWidgets>
include <QtCharts>
class CustomChartView : public QtCharts::QChartView {
protected:
void paintEvent(QPaintEvent* event) override {
QChartView::paintEvent(event);
QChart* chart = chart();
if (!chart) {
return;
}
// Calculate the desired aspect ratio
double aspectRatio = 2.0; // For a 2:1 aspect ratio
// Get the current plot area
QRectF plotArea = chart->plotArea();
// Calculate the new plot area with the desired aspect ratio
double currentWidth = plotArea.width();
double currentHeight = plotArea.height();
double newWidth, newHeight;
if (currentWidth / currentHeight > aspectRatio) {
newHeight = currentWidth / aspectRatio;
newWidth = currentWidth;
} else {
newWidth = currentHeight * aspectRatio;
newHeight = currentHeight;
}
// Center the new plot area
QPointF newTopLeft = plotArea.center() - QPointF(newWidth / 2, newHeight / 2);
QRectF newPlotArea(newTopLeft, QSizeF(newWidth, newHeight));
// Set the new plot area
chart->setPlotArea(newPlotArea);
}
};
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QChart chart;
QLineSeries *series = new QLineSeries();
for (int i = 0; i < 10; ++i) {
series->append(i, i * i);
}
chart.addSeries(series);
CustomChartView chartView(&chart);
chartView.show();
return app.exec();
}
Upvotes: -1