0
def plotbars(hists, bins, labels, filename):
    plt.figure()
    center = (bins[:-1] + bins[1:]) / 2
    width = 0.7 * (bins[1] - bins[0])
    for hist in hists:
        plt.bar(center, hist, align='center', width=width)
    plt.legend(labels)
    plt.savefig(filename)

If I plot histograms like this plotbars([hist1, hist2], bins, ['hist1', 'hist2'], 'histo.png'), this plots the histograms on top of each other. I want to the bars of the histogram to be adjacent. The bin width for each are equal.

4
  • Can you provide an example of what hists is? Commented Jul 4, 2017 at 12:38
  • its the output of np.histogram() Commented Jul 4, 2017 at 12:39
  • It would be much easier for us if you can provide a Minimal, Complete, and Verifiable Example. Commented Jul 4, 2017 at 12:43
  • 1
    Do you mean adjacent in the same figure? Then you have to shift your center to the right in each iteration. For instance to center = [c + offset for c in center], where offset = bins[-1] - bins[0], in every iteration of your for-loop, or some such. Commented Jul 4, 2017 at 12:44

1 Answer 1

1

try using plt.hist instead of plt.bar.

hist1=[x for x in range(0,10)]*10
hist2= [x for x in range(0,10)]*2
plt.hist([hist1,hist2],bins = 10)

Yields this image:

enter image description here

Is this how you would like to see your graph?

Update:

x axis can be properly formatted using the following.

bin_list = [x for x in range(0,11) ]
plt.hist([hist1,hist2], bins=bin_list ,align='left')

Resulting in a proper spaced x axis. For some reason it appears bins must be set as a list for proper spacing of x values.

enter image description here

https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.xticks

For further tweaking you can try to play around with plt.xticks().

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, I'd like a graph that looks like this. But how do I plot x axis properly?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.