Qt之qcustomplot绘柱图(柱图重叠问题)

    //避免柱图重叠,每次绘制之前柱图清除一次
    int plottableCount = ui->qcustomPlot1->plottableCount();
    if (plottableCount != 0)
          ui->qcustomPlot1->clearPlottables();

 
 
    QVector<QString> labels(5);
    QVector<double> values(5);
 
 
    labels[0]=QString("Co");
    labels[1]=QString("H2s");
    labels[2]=QString("O2");
    labels[3]=QString("Gas");
    labels[4]=QString("电量");
 
 
    values[0]=d1;
    values[1]=d2;
    values[2]=d3;
    values[3]=d4;
    values[4]=d5;
 
 
    //QCustomPlot提供的QCPBars来表示柱状图
    QCPBars* bars=new QCPBars(ui->qcustomPlot1->xAxis,ui->qcustomPlot1->yAxis);
    bars->setAntialiased(false);
    bars->setPen(QPen(QColor(0, 168, 140).lighter(130)));
    bars->setBrush(QColor(0, 168, 140));
 
 
    QVector<double> index(5);
    for(int i=0;i<5;++i)
       index[i]=i;
    //QCPBars的setData()的两个参数也是两个向量,只不过第一个向量index的每个元素表示“第几个柱子”,然后后面对应的values表示对应“柱子的值”
    bars->setData(index,values);
 
 
    ui->qcustomPlot1->xAxis->setAutoTicks(false);
    ui->qcustomPlot1->xAxis->setAutoTickLabels(false);
    ui->qcustomPlot1->xAxis->setAutoTickStep(false);
    ui->qcustomPlot1->addPlottable(bars);
    ui->qcustomPlot1->rescaleAxes();
 
 
    double wid=ui->qcustomPlot1->xAxis->range().upper-ui->qcustomPlot1->xAxis->range().lower;
    double cl=bars->width()+(1.0*wid-bars->width()*5)/4;
 
 
    QVector<double> coor;
    for(int i=0;i<5;++i)
            coor.append(ui->qcustomPlot1->xAxis->range().lower+i*cl+bars->width()/2);
    ui->qcustomPlot1->xAxis->setTickVector(coor);
    ui->qcustomPlot1->xAxis->setTickVectorLabels(labels);
    ui->qcustomPlot1->replot();
 

猜你喜欢

转载自blog.csdn.net/u014252478/article/details/80443313
今日推荐