add values to add value in a matplotlib image

Solutions on MaxInterview for add values to add value in a matplotlib image by the best coders in the world

showing results for - "add values to add value in a matplotlib image"
Neila
28 Aug 2018
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")
52