|
| 1 | +""" Horizontal histogram plotting function. """ |
| 2 | + |
| 3 | +from __future__ import absolute_import |
| 4 | +import matplotlib.pyplot as plt |
| 5 | +import numpy as np |
| 6 | + |
| 7 | + |
| 8 | +def horizontal_hist(items, title=None, axis_label=None, color=None, height=10, width=20, reverse=False): |
| 9 | + """ |
| 10 | + Plots a histogram of values and frequencies. |
| 11 | +
|
| 12 | + Arguments: |
| 13 | + items (iterable[any]) => Example, [1, 2, 3, 1, 2] |
| 14 | + title (Optional[str]) => Example, "Resulting histogram". |
| 15 | + axis_label (Optional[str]) => Example, "y-axis". |
| 16 | + color (Optional[str]) => Default: matplotlib's default plot color, a royal blue |
| 17 | + height (Optional[int]) => Default: 10 |
| 18 | + width (Optional[int]) => Default: 20 |
| 19 | + reverse (Optional[bool]) => From top to bottom in order of decreasing frequency or not. |
| 20 | +
|
| 21 | + Returns: |
| 22 | + None, however a matplotlib figure should be produced. |
| 23 | + """ |
| 24 | + |
| 25 | + unique_items, item_counts = np.unique(items, return_counts=True) |
| 26 | + item_counts, unique_items = zip(*sorted(zip(item_counts, unique_items), reverse=reverse)) |
| 27 | + |
| 28 | + pos = np.arange(len(unique_items)) + 0.5 |
| 29 | + plt.figure(figsize=(width, height)) |
| 30 | + plt.barh(pos, item_counts, align='center', color=color) |
| 31 | + plt.yticks(pos, unique_items) |
| 32 | + plt.xlabel('Frequency') |
| 33 | + plt.ylabel(axis_label) if axis_label else None |
| 34 | + plt.title(title) if title else None |
| 35 | + |
| 36 | + plt.show() |
| 37 | + |
| 38 | + |
| 39 | +if __name__ == '__main__': |
| 40 | + items = range(1, 10) * 100 + range(11, 20) * 50 + range(21, 30) * 25 |
| 41 | + horizontal_hist(items, title="Resulting histogram") |
0 commit comments