Search code examples
pythonmatplotlibannotationsscatter-plotsubscript

Matplotlib annotate with subscript and format


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


Solution

  • 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]))