4

I have a histogram in which I want to label the x-axis by bins. The histogram is plotted as a log log graph, but the bins are very specific. The graph:

The Graph

The bins:

bins = [0, 0.035, 0.07, 0.15, 0.5, 1, 3, 10, 40] 

Is there any way I can do this? I believe it would also require getting rid of the current x-axis labels.

1
  • What about ax.set_xticks(bins)? Also, I think it would look better if you added the paramater edgecolor="k" in your plt.hist. Commented Jul 21, 2017 at 4:18

1 Answer 1

7

I wrote an example code for you. Basically, all you need was 'set_xticks' and 'set_xticklabels'.

import numpy as np import matplotlib.pyplot as plt x = [0.01, 0.01, 0.01, 0.04, 0.1, 0.1, 0.4, 0.4, 0.4, 0.4, 0.65, 0.65, 0.65, 2, 7, 7, 7, 7, 7, 7, 7, 7, 18, 18, 18] my_bins = [0.001, 0.035, 0.07, 0.15, 0.5, 1, 3, 10, 40] ind = np.array(my_bins[:-1]) width = np.array([my_bins[i+1]-my_bins[i] for i in range(len(my_bins)-1)]) fig, ax = plt.subplots() ax.hist(x, bins=my_bins) ax.set_xscale('log') ax.set_xticks(ind + width/2) ax.set_xticklabels(('bin1', 'bin2', 'bin3', 'bin4', 'bin5', 'bin6', 'bin7', 'bin8')) plt.show() 
Sign up to request clarification or add additional context in comments.

5 Comments

That worked, except my labels are slightly misaligned with the bins. :)
Great! I think you can adjust the xticks to align your labels. This can be done by modifying the 'ind' and 'width' array.
sorry if im asking an obvious question but how would i adjust these arrays to make the labels go slightly left?
If you try to print the content of 'ind+width/2', you will see a list. Each value in this list stands for the position where you want to show your labels along x-axis. I show the label in the center of each bin.
ok that helps. thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.