Reputation: 185
I need to plot a loglog histogram (bot x and y in log10 scale) using Matplotlib, but the following code isn't showing my desired output:
import matplotlib.pyplot as plt
import numpy as np
fig, ax1 = plt.subplots()
# suppose to have an array x
ax1.hist(x, ec='white', color="red")
plt.xscale("log")
plt.yscale("log")
plt.show()
My desired output is a histogram where x=np.log10(x) and equivalently y=np.log10(y), where each element in y is the height of each bin. I even tried to use a bar plot, but I couldn't solve the problem of the overlapping bins:
import matplotlib.pyplot as plt
import numpy as np
frequency_dict = Counter(x)
new_x = list(frequency_dict.keys())
y = list(frequency_dict.values())
ax1.bar(np.log10(new_x), np.log10(y), ec='white', color="red")
plt.show()
Upvotes: 1
Views: 1525
Reputation: 80554
You can create bins that are distributed evenly in logspace. These bin boundaries can be calculated with np.logspace(min, max, num_bins)
.
from matplotlib import pyplot as plt
import numpy as np
x = np.abs(np.random.normal(500, 200, 1000))
assert x.min() > 0, "all values need to be positive for log scale"
plt.hist(x, bins=np.logspace(np.log10(x.min()), np.log10(x.max()), 15), ec='white', color="red")
plt.loglog()
plt.show()
At the left the histogram with linear axes and at the right with log-log axes. Both histograms using the log-style bins.
Upvotes: 1
Reputation: 4199
You can use "log = True" in the hist function to set the y-axis in log scale. You can manually log the x data before creating histogram. So this is an example that shows how to do that. I hope this is what you are looking for.
import matplotlib.pyplot as plt
import numpy as np
# Simulate a normally distributed dataset
x = np.random.normal(loc = 500, scale = 200, size = 100)
fig, ax = plt.subplots(ncols = 2, figsize=(12,3))
ax[0].hist(x, ec='white', color="red", log = False)
ax[0].set_xlabel('x')
ax[0].set_ylabel('Freq counts')
ax[1].hist(np.log10(x), ec='white', color="red", log = True)
ax[1].set_xlabel('log10(x)')
ax[1].set_ylabel('Freq counts in log scale')
plt.show()
which results in
Upvotes: 0