Search code examples
c++plotaudiohistogram

Plot Histogram from vector data in C++


I'm trying to do a simple task. Draw an Histogram in C++, I'm reading data from a audio file and stored the counted values in a vector.

wav_hist.h

class WAVHist {
  private:
    std::vector<std::map<short, size_t>> counts;

  public:
    WAVHist(const SndfileHandle& sfh) {
        counts.resize(sfh.channels());
    }

    // Mono channel
    WAVHist() {
        counts.resize(1);
    }

    void update(const std::vector<short>& samples) {
        size_t n { };
        for(auto s : samples)
            counts[n++ % counts.size()][s]++;
    }

    void dump(const size_t channel) const {
        for(auto [value, counter] : counts[channel])
            std::cout << value << '\t' << counter << '\n';
    }

    void mid_channel(const std::vector<short>& samples) {
        for(auto i = 0; i < samples.size()/2; i++)
            counts[0][(samples[2*i] + samples[2*i+1]) / 2]++;
    }

The final output is shown in the dump function (freq count_value). How can I transform this to draw an histogram?

output desired

Something like gnuplotdoes.

enter image description here


Solution

  • The C++ standard itself does not provide any classes for visualization or graphical user interfaces. There are, of course, many frameworks and libraries available for that.

    Since you already know gnuplot, you may be interested in a C++ interface for gnuplot. Other alternatives include Qt Charts or Boost.Python.

    See also this question.