Open In App

C++ Program to Draw a Histogram

Last Updated : 05 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

A histogram is a graphical representation of the distribution of a set of data. It displays the data in a bar graph format, where each bar represents the count or frequency of data points falling within a specific range or bin. Histograms are commonly used in data analysis and visualization to provide insights into the distribution of data and identify trends or patterns.

In C++, histograms can be drawn using various graphical libraries such as the Simple DirectMedia Layer (SDL) or the OpenGL Utility Toolkit (GLUT), or by using ASCII characters to draw the bars in the console window. A basic histogram program can be implemented using loops and conditional statements to calculate the bin counts and draw the bars, while more advanced programs can use object-oriented programming principles and advanced graphics techniques to create interactive and customizable histograms.

Approach for creating Histogram in C++

To create a histogram in C++, the first step is to collect the data and determine the range or bins for the histogram. The data is then sorted into the appropriate bins, and the count or frequency of data points in each bin is calculated. The counts or frequencies are then represented as bars in the histogram, with the height of each bar indicating the count or frequency of data points in the corresponding bin.

The code uses a simple approach to draw a histogram using ASCII characters in the console. The main steps to implement the topic are mentioned below:

  • Input: The program takes a vector of integers as input.
  • Find the maximum value in the input data. This is used to determine the scaling factor for the histogram.
  • Calculate the scaling factor to fit the data in the console window. This is done by dividing the maximum value in the data by the maximum height of the histogram (which is set to 20 characters) and adding 1.
  • Draw the histogram. This is done by iterating over the rows of the histogram from top to bottom. For each row, the program draws the vertical axis, the data bars, and the x-axis labels. The vertical axis is drawn as a line of ‘-‘ characters, and the data bars are drawn as ‘#’ characters if the value in the input data is greater than or equal to the current row index times the scaling factor.
  • Output the histogram to the console. This is done by printing the ASCII characters to the console using the cout statement.

The code uses standard C++ libraries, including iostream and vector. It defines a drawHistogram function that takes a vector of integers as input and outputs the histogram to the console. The main function defines a sample data set and calls the drawHistogram function to draw the histogram.

Below is the implementation of the above approach:

C++




// C++ Program to print histogram
// without using external library
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
  
using namespace std;
  
// Driver main
int main()
{
    // Vector declared
    vector<int> data = { 13, 5, 8, 9, 4, 2, 1 };
  
    // max velue
    int max_value = *max_element(data.begin(), data.end());
  
    // Histogram
    for (int i = max_value; i >= 0; --i) {
        cout.width(2);
        cout << i << " | ";
  
        // Marking the values
        for (int j = 0; j < data.size(); ++j) {
            if (data[j] >= i) {
                cout << "x ";
            }
            else {
                cout << "  ";
            }
        }
        cout << endl;
    }
    cout << "---------------------------------------"
         << endl;
    cout << "    ";
  
    // Data printed
    for (int i = 0; i < data.size(); ++i) {
        cout << data[i] << " ";
    }
  
    return 0;
}


Output

13 | x             
12 | x             
11 | x             
10 | x             
 9 | x     x       
 8 | x   x x       
 7 | x   x x       
 6 | x   x x       
 5 | x x x x       
 4 | x x x x x     
 3 | x x x x x     
 2 | x x x x x x   
 1 | x x x x x x x 
 0 | x x x x x x x 
---------------------------------------
    13 5 8 9 4 2 1 

Explanation of the Code

This program takes a vector of integers as input and draws a histogram using ASCII characters in the console. The height of the histogram is set to a maximum of 20 characters, and the scaling factor is calculated based on the maximum value in the input data. The program then draws the vertical axis, the data bars, the horizontal axis, and the x-axis labels. Finally, the program outputs the histogram to the console.

Time Complexity: 

Time Complexity = O(n * m)
  • Finding the maximum value in the data: O(n), where n is the size of the data vector
  • Calculating the scaling factor: O(1)
  • Drawing the vertical axis: O(n)
  • Drawing the data bars: O(n * m), where m is the maximum height of the histogram (20 in this case)
  • Drawing the horizontal axis: O(n)
  • Drawing the x-axis labels: O(n)

Therefore, the overall time complexity of the code is O(n * m), where n is the size of the input data and m is the maximum height of the histogram.

 Space Complexity: 

Space Complexity = O(n)
  • Input data: O(n), where n is the size of the data vector
  • Other variables: O(1)

Therefore, the overall space complexity of the code is O(n), where n is the size of the input data.

Note: Note that the space complexity does not take into account the space used by the console window to display the histogram, as this is outside the scope of the code. The actual space used by the program may be greater if the console window size is increased or if the program is modified to use a graphical library to display the histogram.

Conclusion

A histogram is a useful tool for visualizing the distribution of data and identifying trends and patterns. In C++, a histogram can be implemented using loops and conditional statements to calculate bin counts and drawbars, or by using graphical libraries such as SDL or GLUT to create interactive and customizable histograms. The time and space complexity of the code can be analyzed to determine the efficiency of the implementation and identify opportunities for optimization. Understanding the time and space complexity of a program is crucial in optimizing its performance and ensuring that it can handle large datasets efficiently. Overall, histograms are a powerful tool for data analysis and visualization, and their implementation in C++ is a useful skill for anyone working with data.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads