0

I'm trying to add annotations with subscripts to my scatterplot. The problem is that the formatting doesn't appear to be working for the integers in the double digits. The annotation only turns the first symbol into a subscript, as shown in the figure below. Does anyone know how to fix this?

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

rnd.seed(1234)

#Generate data
n = 12 #Number of vehicles
N = [i for i in range(1,n+1)] #Set of vehicles
V = [0] + N #Set of all nodes
q = {i: rnd.randint(1,10) for i in N} #Number of goods to be transported to each customer

#Generate coordinates
loc_x = rnd.rand(len(V))*300
loc_y = rnd.rand(len(V))*500

plt.scatter(loc_x[1:], loc_y[1:], c='b')
for i in N:
    plt.annotate('$q_{}={}$'.format(i, q[i]),(loc_x[i]+2, loc_y[i]))

Failed subscripts

Alex
  • 941
  • 3
  • 11
  • 23

2 Answers2

2

The following will fix your problem.

Essentially, you need to add curly braces around the subscript when your subscript is longer than a single character. However, because curly braces also relate to the format method, the extra braces must be escaped by more braces to be interpreted as we desire.

plt.scatter(loc_x[1:], loc_y[1:], c='b')
for i in N:
    plt.annotate('$q_{{{}}}={}$'.format(i, q[i]),(loc_x[i]+2, loc_y[i]))
jwalton
  • 5,286
  • 1
  • 18
  • 36
  • Thanks for answering my question. I have a small followup which is unrelated to the main question that you might be able to help me with. Currently the annotation in the topright is shown outside of the plot window. Do you know how to prevent this? – Alex Feb 18 '19 at 15:53
  • One option would be to simply alter the x-limits ```plt.gca().set_xlim(-10, 310)```. Another option could be to add alignment arguments to ```plt.annotate```. Something like ```verticalalignment='bottom', horizontalalignment='center'``` might give you what you want – jwalton Feb 18 '19 at 16:05
0

This would help you and could be more intuitive. Instead of using format use the string formatting with %. Also take care of the braces {} in latex formatting. You need to put braces around all of the text that you want to appear as subscript.

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

rnd.seed(1234)

#Generate data
n = 12 #Number of vehicles
N = [i for i in range(1,n+1)] #Set of vehicles
V = [0] + N #Set of all nodes
q = {i: rnd.randint(1,10) for i in N} #Number of goods to be transported to each customer

#Generate coordinates
loc_x = rnd.rand(len(V))*300
loc_y = rnd.rand(len(V))*500

plt.scatter(loc_x[1:], loc_y[1:], c='b')
for i in N:
    plt.annotate(r'$q_{{%d}_{%d}}$'%(i, q[i]),(loc_x[i]+2, loc_y[i]))
jkhadka
  • 2,443
  • 8
  • 34
  • 56