Rehankhan Daya
Rehankhan Daya

Reputation: 59

.annotate function in matplotlib causing coordinates to not match axis

Data is in table variable

table=list(zip(cities1, coords[:, 0], coords[:, 1]))

[('acura', -0.17547704744098544, -0.6166976976480806),
 ('audi', 0.3532486941005613, -0.300526194463427),
 ('bmw', 0.7795858855225921, 0.22066166376952917),
 ('honda', -0.7664008669199922, -0.08707404835184429),
 ('hyundai', -0.0976861347111208, 1.1308973697451388),
 ('infiniti', 0.25553899375818806, -0.8313428105248483),
 ('kia', 0.20783662466651553, 1.1170395030334848),
 ('nissan', -0.5823225686931098, -0.5084012295485035),
 ('pontiac', 0.6573317212955139, -0.6012122629097848),
 ('toyota', -0.6316553015781629, 0.47665570689833636)]

Then I set the font of the plot

font0 = FontProperties()
font = font0.copy()

## Change the size of the font
font.set_size('xx-large')

Then I make the plot with .annotate

fig, ax = plt.subplots(figsize=(5, 5))

ax.set(xlim=(-2, 2), ylim=(-2, 2))

for label, x, y in zip(cities1, coords[:, 0], coords[:, 1]):
    ax.annotate(
        label,
        xy = (x, y), xytext = (-20, 20), xycoords='axes fraction',
        fontproperties=font,
        textcoords = 'offset points', ha = 'right', va = 'bottom',
        bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.5),
        arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0',))


plt.savefig('MDS.png')

I am confused where the code goes wrong in the last block of code? I assume this is where the error is since it makes the plot look like this.

enter image description here

Upvotes: 1

Views: 163

Answers (1)

r-beginners
r-beginners

Reputation: 35115

If you change the axis reference to 'data', you will get a numbered graph.

ax.annotate(
    label,
    xy = (x, y), xytext = (-20, 20), xycoords='data', # update
    fontproperties=font,
    textcoords = 'offset points', ha = 'right', va = 'bottom',
    bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.5),
    arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0',))

enter image description here

Upvotes: 2

Related Questions