adding labels to histogram bars in matplotlib

Solutions on MaxInterview for adding labels to histogram bars in matplotlib by the best coders in the world

showing results for - "adding labels to histogram bars in matplotlib"
Alessandra
15 Sep 2018
1import numpy as np
2import pandas as pd
3import matplotlib.pyplot as plt
4
5# Bring some raw data.
6frequencies = [6, -16, 75, 160, 244, 260, 145, 73, 16, 4, 1]
7
8# In my original code I create a series and run on that,
9# so for consistency I create a series from the list.
10freq_series = pd.Series.from_array(frequencies)
11
12x_labels = [108300.0, 110540.0, 112780.0, 115020.0, 117260.0, 119500.0,
13            121740.0, 123980.0, 126220.0, 128460.0, 130700.0]
14
15# Plot the figure.
16plt.figure(figsize=(12, 8))
17ax = freq_series.plot(kind='bar')
18ax.set_title('Amount Frequency')
19ax.set_xlabel('Amount ($)')
20ax.set_ylabel('Frequency')
21ax.set_xticklabels(x_labels)
22
23
24def add_value_labels(ax, spacing=5):
25    """Add labels to the end of each bar in a bar chart.
26
27    Arguments:
28        ax (matplotlib.axes.Axes): The matplotlib object containing the axes
29            of the plot to annotate.
30        spacing (int): The distance between the labels and the bars.
31    """
32
33    # For each bar: Place a label
34    for rect in ax.patches:
35        # Get X and Y placement of label from rect.
36        y_value = rect.get_height()
37        x_value = rect.get_x() + rect.get_width() / 2
38
39        # Number of points between bar and label. Change to your liking.
40        space = spacing
41        # Vertical alignment for positive values
42        va = 'bottom'
43
44        # If value of bar is negative: Place label below bar
45        if y_value < 0:
46            # Invert space to place label below
47            space *= -1
48            # Vertically align label at top
49            va = 'top'
50
51        # Use Y value as label and format number with one decimal place
52        label = "{:.1f}".format(y_value)
53
54        # Create annotation
55        ax.annotate(
56            label,                      # Use `label` as label
57            (x_value, y_value),         # Place label at end of the bar
58            xytext=(0, space),          # Vertically shift label by `space`
59            textcoords="offset points", # Interpret `xytext` as offset in points
60            ha='center',                # Horizontally center label
61            va=va)                      # Vertically align label differently for
62                                        # positive and negative values.
63
64
65# Call the function above. All the magic happens there.
66add_value_labels(ax)
67
68plt.savefig("image.png")
Luisa
07 Apr 2019
1# Bring some raw data.
2frequencies = [6, -16, 75, 160, 244, 260, 145, 73, 16, 4, 1]
3
4freq_series = pd.Series(frequencies)
5
6y_labels = [108300.0, 110540.0, 112780.0, 115020.0, 117260.0, 119500.0, 
7            121740.0, 123980.0, 126220.0, 128460.0, 130700.0]
8
9# Plot the figure.
10plt.figure(figsize=(12, 8))
11ax = freq_series.plot(kind='barh')
12ax.set_title('Amount Frequency')
13ax.set_xlabel('Frequency')
14ax.set_ylabel('Amount ($)')
15ax.set_yticklabels(y_labels)
16ax.set_xlim(-40, 300) # expand xlim to make labels easier to read
17
18rects = ax.patches
19
20# For each bar: Place a label
21for rect in rects:
22    # Get X and Y placement of label from rect.
23    x_value = rect.get_width()
24    y_value = rect.get_y() + rect.get_height() / 2
25
26    # Number of points between bar and label. Change to your liking.
27    space = 5
28    # Vertical alignment for positive values
29    ha = 'left'
30
31    # If value of bar is negative: Place label left of bar
32    if x_value < 0:
33        # Invert space to place label to the left
34        space *= -1
35        # Horizontally align label at right
36        ha = 'right'
37
38    # Use X value as label and format number with one decimal place
39    label = "{:.1f}".format(x_value)
40
41    # Create annotation
42    plt.annotate(
43        label,                      # Use `label` as label
44        (x_value, y_value),         # Place label at end of the bar
45        xytext=(space, 0),          # Horizontally shift label by `space`
46        textcoords="offset points", # Interpret `xytext` as offset in points
47        va='center',                # Vertically center label
48        ha=ha)                      # Horizontally align label differently for
49                                    # positive and negative values.
50
51plt.savefig("image.png")
queries leading to this page
bar stacked histogram matplotlib pythonhow to get numbers on top of nar chart pyplotpyplot bar add labelsx labels as text in bar pythonmatplotlib bar plot label only few barsplt horizontal bar value labellinghow to add labels to values in a barchart pythongetting numeric value of data in bar chart pyplotmatplotlib add labels to barhadding labels to histogram bars in matplotlibi cant see the labels on my barplot in pythonpython show data labels in barplotlabel on bar matplotlibhow to add data labels in bar chart in pythonadding the text label for each barhow to label bar in matplotlibhow to plot bar with label pythonadd bar total in barplot matplotlibmatplotlib chart label histogramadd label to histogram matplotlibmatplotlib bar little x labelsplt bar chart with text labelpython bar graph with labelsbarplot x axis labels matplotlibmatplto add label to baradd label above bar histogram matplotlibadd label to bar matpltolibbar graph labels with same name matplotlibhow to add values to matplot labeladd another data in bar chart mayplotlibmatplotlib add data labels to bar charthow to make a bar chart with labels in pythonprint label in barchart python matplotlibtick label to each bar in matplotlibhow to put bar label in python plotadd labels with numbers pythonadd numbers to label plot pythonhow to put names on bar chart matplotliblabel a chart values in matplotlibadd label to bar chart matplotlibmatplotlib histogram show bar valuehow to give labels to hist matplotlibadd labels to histogram plot pythonbar chart matplotlib label numberplotting values with text bar6 histogram bars matplotlib pythonhow to lable the bars in a bar chart using matplotbaradd x labels below bar plot pythonbarchart labelpyplot value labelsshow data labels in bar graph ax barlabel below python graphsmatplotlib add labels to bar chartmatplotlib histogram bar charthow to add labels to values in a barchart python easypyplot add labels chartmatplotlib adding information to a bar charthow to add data points to bar graph matplotlibdata labels in plt bar in pythonhow to label bar graph in pythonmatplotlib histogram with label barsmatplotlib barh add labelsplt hist label barspython bar plot add values textadding labels to histogram bars in matplotlib