2

I'm wondering how to have a log-log plot for visualizing the frequency of elements in a list, for example:

my_list=[1,2,3,3,3,4,1,2,5,2,10,4,5,3,3,3,2,1]

I plotted data using a histogram:

plt.hist(my_list, label='Frequency Distribution of matches')
plt.legend()
plt.ylabel('Frequency')

But it would be better to visualize it as log-log.

tdy
  • 36,675
  • 19
  • 86
  • 83
Math
  • 191
  • 2
  • 5
  • 19

1 Answers1

2

plt.hist includes a log param, which behaves like plt.yscale('log') since it only scales the y-axis:

log: If True, the histogram axis will be set to a log scale.

To also scale the x-axis, combine it with plt.xscale('log'):

plt.hist(my_list, log=True)
plt.xscale('log')

If you want equal-width bars, define bins as 10 ** edges:

start, stop = np.log10(min(my_list)), np.log10(max(my_list))
bins = 10 ** np.linspace(start, stop, 10)

plt.hist(my_list, log=True, bins=bins)
ax.set_xscale('log')

To get a log-log line plot of the frequencies, use plt.stairs (requires matplotlib 3.4+) with np.histogram:

plt.stairs(*np.histogram(my_list))
plt.yscale('log')
plt.xscale('log')

tdy
  • 36,675
  • 19
  • 86
  • 83
  • 1
    thank you, tdy. Would it be possible to plot, instead of a histogram, a line plot using log=True? – Math Nov 24 '21 at 00:26
  • 1
    @Math do you mean a log-log line plot of frequencies? if so, use [`plt.stairs`](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.stairs.html) (requires matplotlib 3.4+) with [`np.histogram`](https://numpy.org/doc/stable/reference/generated/numpy.histogram.html) (answer updated) – tdy Nov 24 '21 at 00:35
  • 1
    see https://stackoverflow.com/a/68201845/13138364 for more details on stair plots – tdy Nov 24 '21 at 00:42