#include "qcustomplot.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv); QCustomPlot customPlot;
customPlot.resize(700, 500);
customPlot.show(); QCPAxis* keyAxis = customPlot.xAxis;
QCPAxis* valueAxis = customPlot.yAxis; QCPBars* fossil = new QCPBars(keyAxis, valueAxis); // 使用xAxis作为柱状图的key轴,yAxis作为value轴
fossil->setAntialiased(false); // 为了更好的边框效果,关闭抗齿锯
fossil->setName("Fossil fuels"); // 设置柱状图的名字,可在图例中显示
fossil->setPen(QPen(QColor(0, 168, 140).lighter(130))); // 设置柱状图的边框颜色
fossil->setBrush(QColor(0, 168, 140)); // 设置柱状图的画刷颜色 // 为柱状图设置一个文字类型的key轴,ticks决定了轴的范围,而labels决定了轴的刻度文字的显示
QVector<double> ticks;
QVector<QString> labels;
ticks << 1 << 2 << 3 << 4 << 5 << 6 << 7;
labels << "USA" << "Japan" << "Germany" << "France" << "UK" << "Italy" << "Canada";
QSharedPointer<QCPAxisTickerText> textTicker(new QCPAxisTickerText);
textTicker->addTicks(ticks, labels);
keyAxis->setTicker(textTicker); // 设置为文字轴 keyAxis->setTickLabelRotation(60); // 轴刻度文字旋转60度
keyAxis->setSubTicks(false); // 不显示子刻度
keyAxis->setTickLength(0, 4); // 轴内外刻度的长度分别是0,4,也就是轴内的刻度线不显示
keyAxis->setRange(0, 8); // 设置范围
keyAxis->setUpperEnding(QCPLineEnding::esSpikeArrow); valueAxis->setRange(0, 12.1);
valueAxis->setPadding(35);
valueAxis->setLabel("Power Consumption in\nKilowatts per Capita (2007)");
valueAxis->setUpperEnding(QCPLineEnding::esSpikeArrow);
QVector<double> fossilData;
fossilData << 0.86 * 10.5 << 0.83 * 5.5 << 0.84 * 5.5 << 0.52 * 5.8 << 0.89 * 5.2 << 0.90 * 4.2 << 0.67 * 11.2;
fossil->setData(ticks, fossilData); return a.exec();
}
效果图如下: