0

I am using a dictionary "my_dictionary" containing key and a list containing two int items.
Dictionary - {key : [men_mean, women_mean]}.
Counts:
Values of men_mean and women_mean are close to 2000.
Total keys are 400.

I am getting following error:

Error:

----> 5         ax.annotate('{}',format(height), xy=(rect.get_x() + rect.get_width() / 2, height), xytext=(0,maximum), 
textcoords="offset points", ha='center', va='bottom')

TypeError: annotate() got multiple values for argument 'xy'

Code:

import matplotlib
import matplotlib.pyplot as plt
import numpy as np


labels, list_item = zip(*sorted(my_dictionary.items())
for key, item in my_dictionary.items():
    men_means.append(item[0])
    women_means.append(item[1])


x = np.arange(len(labels))  # the label locations
width = 0.35  # the width of the bars

fig, ax = plt.subplots()
rects1 = ax.bar(x - width/2, men_means, width, label='Men')
rects2 = ax.bar(x + width/2, women_means, width, label='Women')

# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()


def autolabel(rects, maximum):
    """Attach a text label above each bar in *rects*, displaying its height."""
    for rect in rects:
        height = rect.get_height()
        ax.annotate('{}'.format(height),
                    xy=(rect.get_x() + rect.get_width() / 2, height),
                    xytext=(0, maximum),  # 3 points vertical offset
                    textcoords="offset points",
                    ha='center', va='bottom')


autolabel(rects1, max(men_means))
autolabel(rects2, max(women_means))

fig.tight_layout()

plt.show()
MartenCatcher
  • 2,713
  • 8
  • 26
  • 39
usav
  • 1
  • 2
  • The code you have given doesn't yield the error you have given, as it in fact fails much earlier to first a syntax error due to an unmatched parenthesis, then a name error due to an undeclared name `my_dictionary` – Hymns For Disco Jan 23 '20 at 08:31
  • Yes. This is not full code. Dictionary code is separate and big, so I didn't posted entire code. Sorry. But I did mentioned example dictionary for reference. – usav Jan 23 '20 at 09:55

1 Answers1

1

The problem is the comma , between {} and format(), it should be dot .:

ax.annotate('{}'.format(height), ...)

with a comma, the function annotate considers that {} is the first argument and format(height) is the second argument. since the second argument of the function is xy, it thinks you've passed two values to xy, one by position, and then one by keyword xy=.

Instead, what you wanted to do is to pass a formatted string '{}'.format() to the first argument (s) of the function

Diziet Asahi
  • 38,379
  • 7
  • 60
  • 75