QCustomPlot Discussion and Comments

How to add legend to SubplotReturn to overview

Hello guys,

I am just beginning to program using this fantastic library. The quality of the plots is awesome, better than anything, including Matlab. Although I thoroughly studied the examples, there is a question that still is unsolved for me:

How do I add a Legend to Sub-Plots? How would you add legends to the graphs e.g. in AdvancedAxesDemo?

Maybe someone could help me with this. I an sure this is super trivial, but somehow, I got stuck.

Cheers,
Jan

Here's how you could do it:

  // create new axis rect and add it to the plot layout:
  QCPAxisRect *ar = new QCPAxisRect(ui->customPlot);
  ui->customPlot->plotLayout()->addElement(0, 1, ar);
  
  // setup an extra legend for that axis rect:
  QCPLegend *arLegend = new QCPLegend;
  ar->insetLayout()->addElement(arLegend, Qt::AlignTop|Qt::AlignRight);
  arLegend->setLayer("legend");
  ui->customPlot->setAutoAddPlottableToLegend(false); // would add to the main legend (in the primary axis rect)
  
  // create a graph in the new axis rect:
  QCPGraph *graph = ui->customPlot->addGraph(ar->axis(QCPAxis::atBottom), ar->axis(QCPAxis::atLeft));
  // add a legend item to the new legend, representing the graph:
  arLegend->addItem(new QCPPlottableLegendItem(arLegend, graph));
  
  // this is how to remove the legend item again (e.g. before graph removal):
  arLegend->remove(arLegend->itemWithPlottable(graph));

Adding and removing from the legend is a little less convenient/automated as for the default primary legend. I've noticed there's an easier way that QCustomPlot could provide: the QCPAbstractPlottable::addToLegend/removeFromLegend could have an optional QCPLegend* parameter which could make it usable also for non-default legends. I'll try to add that in version 1.3.

Thanks for your support! I really appreciate your effort and commitment.

- Jan

Thank you very much!! :-)

Thank you very much!! :-)

Thank you very much!! :-)

Thank you very much!! :-)