Shapeworks Studio  2.1
Shape analysis software suite
bargraph.cpp
1 #include "bargraph.h"
2 
3 #include <QPainter>
4 #include <QFontMetrics>
5 #include <QMouseEvent>
6 #include <QRect>
7 #include <QTextItem>
8 #include <sstream>
9 #include <cmath>
10 #include <iostream>
11 
12 BarGraph::BarGraph(QWidget *parent) :
13  QWidget(parent),
14  max_val(100.),
15  min_val(0.),
16  barwidth(10),
17  margin(5),
18  use_log_(true)
19 {}
20 
21 BarGraph::~BarGraph() {}
22 
23 void BarGraph::setLogScale(bool b) {
24  use_log_ = b;
25  recalcBasicValues();
26 }
27 
28 void BarGraph::setData(std::vector<double> val)
29 {
30  min_val = *std::min_element(val.begin(),val.end());
31  max_val = *std::max_element(val.begin(),val.end());
32  values.clear();
33  for (size_t i = 0; i < val.size(); i++)
34  values.push_back(val[i]);
35  recalcBasicValues();
36  setMinimumSize( (int)(margin*values.size()*2),200+margin*5);
37 }
38 
39 void BarGraph::paintBargraph(QPainter &painter)
40 {
41  QPen p(Qt::black);
42  p.setWidth(2);
43  painter.setPen(p);
44  painter.setBrush(Qt::blue);
45 
46  for(size_t i=0, s = values.size(); i < s; ++i)
47  {
48  painter.drawRect(bars[i]);
49  //numbered eigen value on x axis
50  painter.drawText(barwidth*(i+0.5)+margin*(i+1),height()- 20,QString::number(i));
51  }
52  //X label
53  painter.drawText(2*margin,height()- 5,"Eigenvalues");
54  // Y Label
55  int num_steps = use_log_?(static_cast<int>(log10(max_val)) -
56  static_cast<int>(log10(min_val))+1):5;
57  num_steps = std::max(1,num_steps);
58  int start = static_cast<int>(use_log_?log10(min_val):0);
59  int separation = (height() - 45) / num_steps;
60  for (int i = 0; i < num_steps; i++) {
61  std::stringstream ss;
62  if (use_log_) {
63  ss << "_1e" << (start+i);
64  painter.drawText(width() - 45,
65  height() - 75 - separation * i,QString(ss.str().c_str()));
66  } else {
67  ss << "_" << static_cast<int>(start + (max_val / num_steps) * i);
68  painter.drawText(width() - 45,
69  height() - 45 - separation * i,QString(ss.str().c_str()));
70  }
71  }
72 }
73 
74 void BarGraph::paintEvent(QPaintEvent *event)
75 {
76  QPainter painter(this);
77  paintBargraph(painter);
78 }
79 
80 
81 void BarGraph::resizeEvent(QResizeEvent *event)
82 {
83  recalcBasicValues();
84 }
85 
86 void BarGraph::recalcBasicValues()
87 {
88  int sz = std::max(1,static_cast<int>(values.size()));
89  barwidth = std::max(margin, (int)((width()-(margin*values.size()))/sz));
90  int h = height() - 45;
91  if(bars.size() != values.size())
92  bars.resize(values.size());
93  int x = margin;
94  for(size_t i=0, s = values.size(); i < s; ++i)
95  {
96  double val = use_log_?(log10(values[i])-log10(min_val)):(values[i]-min_val);
97  double range = use_log_?(log10(max_val) - log10(min_val)):(max_val - min_val);
98  int barheight = static_cast<int>(val * h / (range));
99  bars[i].setRect(x,5 + h - barheight,barwidth, barheight);
100  x += margin + barwidth;
101  }
102 }