我正在尝试将带有下标的注释添加到我的散点图中。问题在于格式似乎不适用于两位数中的整数。注释仅将第一个符号变成下标,如下图所示。有人知道如何解决这个问题吗?
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]))
答案 0 :(得分:1)
以下内容将解决您的问题。
基本上,当下标长于单个字符时,需要在下标周围添加花括号。但是,由于花括号也与format方法有关,因此必须用更多的花括号将多余的花括号转义,以便我们进行解释。
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]))
答案 1 :(得分:0)
这将对您有所帮助,并且可能更直观。将string formatting与format
一起使用,而不是使用%
。还要注意乳胶格式中的括号{}
。您需要在要显示为下标的所有文本周围加上大括号。
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]))