Search code examples
pythonpandashistogramvisualizationgraph-visualization

Make a histogram for a pandas dataframe where the columns are the individual bins


I have a dataframe that looks like the following:

Blue Green Red
1.0 27.0 30.0
24.0 3.0 22.0
3.0 3.0 2.0
5.0 0.0 5.0
2.0 5.0 6.0
10.0 20.0 7.0

I want to make a histogram with each of the column names in as the bins on the x-axis, and the summed values of the numbers as the bar heights. How can I do this, as most of the visualization library examples I've seen have not used the columns themselves as the bins. Any visualization library is fine.


Solution

  • Based on your description, I think you need a generic bar chart which can be created like this

    import matplotlib.pyplot as plt
    import pandas as pd
    
    # Example dataframe
    df = pd.DataFrame({'Blue': [1, 2, 3], 'Green': [2, 3, 4], 'Red': [3, 4, 5]})
    
    # Calculate the sum of each column
    column_sums = df.sum()
    
    # Plot the bar chart
    column_sums.plot(kind='bar', color=['blue', 'green', 'red'])
    plt.show()
    

    enter image description here