0

I need to plot a hist with bot logarithmic y and x-axis, but I'd like also to have hist's bins displayed of same size. enter image description here

How can I achieve this result with the following code (the x used is very long so I have intentionally avoided to insert it):

import matplotlib as plt
import numpy as np

fig, ax1 = plt.subplots()

hist, bins, _ = ax1.hist(x, log=True, color="red", rwidth=0.5)
plt.xscale("log")
np_x = np.array(x)
print("np_x.mean() = " + str(np_x.mean()))
plt.axvline(np_x.mean() * 1.1, color='lime', linestyle='dashed', linewidth=3,
            label='Mean: {:.2f}'.format(np_x.mean()))

handles, labels = ax1.get_legend_handles_labels()
binwidth = math.floor(bins[1] - bins[0])
mylabel = "Binwidth: {}".format(binwidth) + ", Bins: {}".format(len(hist))
red_patch = mpatches.Patch(color='red', label=mylabel)
handles = [red_patch] + handles
labels = [mylabel] + labels
ax1.legend(handles, labels)

plt.xlabel(x_label)
plt.ylabel(y_label)
plt.show()
  • I don't think I understand what you're asking. You set the bin-width as 5410, SInce the x-axis is on a log-scale, the "width" of 5410 is visually smaller as you move to the right. – lsterzinger Apr 24 '20 at 20:14
  • [This post](https://stackoverflow.com/questions/47850202/plotting-a-histogram-on-a-log-scale-with-matplotlib?rq=1) tackles a logarithmic histogram. Note that the binwidth isn't constant. Does it solve your question? (Also note that you are importing pyplot the wrong way, it should be `import matplotlib.pyplot as plt`) – JohanC Apr 24 '20 at 20:42
  • You need to leave out `rwidth=0.5` from `plt.hist` to get the correct widths. Then the width will visually be narrower to the right. Note that `log=True` here doesn't change the bins, it only changes the way the x-axis is displayed. You can add `ec='white'` to see a space between the bars. – JohanC Apr 24 '20 at 20:59

0 Answers0