Search code examples
matplotlibhistogram

Remove the color of the touching bars in plt.bar


So i have two problems:

  1. the density of my histogram didn't had up to 1 while setting density = True in my code. see the following code:
plt.hist(my_data, 25, histtype = 'step', edgecolor ='skyblue', alpha = 0.7, density = True, label = '17GHz',)
plt.title('Horn 4', fontsize = 'x-large')
plt.xlabel('Percentage of zeroes in the file [%]')
plt.ylabel('Counts')
plt.xticks(rotation = 45)  # Rotate x-axis labels for better readability
plt.xticks(np.arange(0, 110, 5)) # Adjust the number of x-axis ticks # start, stop, step
plt.legend()

and plot

enter image description here

So first, why is that so ?? is there a way to fix this ? According to this stack subject (numpy histogram cumulative density does not sum to 1), I used plt.bar which led to my second problem

  1. I can't have the same formating with plt.bar as with np.hist... How do I remove the edge color of the touching bars so that it looks like the above figure?

enter image description here

plt.bar(bins_h4_19[:-1], probability_densities_h4_19, width = np.diff(bins_h4_19), align='edge', edgecolor='skyblue',   color ='white', label = '19 GHz')
plt.bar(bins_h4_17[:-1], probability_densities_h4_17, width = np.diff(bins_h4_17), align='edge', edgecolor='purple',   color = '#FF000000', label = '17 GHz')
plt.xlabel('Percentage of zeroes in the file [%]')
plt.ylabel('Probability Density')
plt.title('Horn 4')
plt.show()

Solution

  • So after a lot of searching, I realised that I wanted the y axis to be the probability density that my data falls into that bins. So I calculated this manually and plotted it with plt.stairs and it worked just fine. Here is my code:

    # plt.hist returns: The values of the histogram bins, The edges of the bins
    hist_wd, bins_wd, _ = plt.hist(wd_column, bins = 25, alpha=0.6, edgecolor = 'b')
    
    # add this to hide the plot
    plt.close()
    
    # Calculate the bin width
    bin_width_wd = bins_wd[1] - bins_wd[0]
    
    # Manually normalize the histogram counts to get the probability density
    hist_density_wd = hist_wd / (len(wd_column))
    
    plt.figure(figsize = (10,4))
    plt.stairs(hist_density_wd, bins_wd, linewidth=2, color = 'blue'  )
    

    enter image description here