在数学模式下将变量编写为下标 [英] Writing variables as subscripts in math mode

查看:126
本文介绍了在数学模式下将变量编写为下标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用for循环绘制分布图以绘制一些数据.现在,我想根据循环计数器将这些分布标记为数学符号中的下标.这就是我目前所处的位置.

I am trying to plot some data, using a for loop to plot distributions. Now I want to label those distributions according to the loop counter as the subscript in math notation. This is where I am with this at the moment.

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

mean = [10,12,16,22,25]
variance = [3,6,8,10,12]
x = np.linspace(0,40,1000)
for i in range(4):
    sigma = np.sqrt(variance[i])
    y = mlab.normpdf(x,mean[i],sigma)
    plt.plot(x,y,label=$v_i$) # where i is the variable i want to use to label. I should also be able to use elements from an array, say array[i] for the same.
    plt.xlabel("X")
    plt.ylabel("P(X)")
plt.legend()
plt.axvline(x=15, ymin=0, ymax=1,ls='--',c='black')    
plt.show()

这是行不通的,而且我无法将变量保持在数学符号的$ $符号之间,因为该变量被解释为文本.有没有办法将变量放入$ $表示法中?

This doesn't work, and I can't keep the variable between the $ $ signs of the math notation, as it is interpreted as text. Is there a way to put the variable in the $ $ notation?

推荐答案

原始问题已被编辑,该答案已经更新以反映这一问题.

当尝试在matplotlib中使用LaTeX格式时,必须使用以r""表示的原始字符串.

When trying to work with LaTeX formatting in matplotlib you must use raw strings, denoted by r"".

下面给出的代码将遍历range(4)并使用i'th均值和方差进行绘制(如您最初所做的那样).它还将使用label=r'$v_{}$'.format(i+1)为每个图设置label.这种字符串格式只是将{}替换为{} c6>,在这种情况下为i+1.通过这种方式,您可以使图的标签自动化.

The code given below will iterate over range(4) and plot using i'th mean and variance (as you originally have done). It will also set the label for each plot using label=r'$v_{}$'.format(i+1). This string formatting simply replaces the {} with whatever is called inside format, in this case i+1. In this way you can automate the labels for your plots.

我已经将plt.axvline(...)plt.xlabel(...)plt.ylabel(...)for循环中删除了,因为您只需要调用一次即可.出于相同的原因,我还从for循环中删除了plt.legend(),并删除了其参数.如果在plt.plot()中提供关键字参数label,则可以在绘制图形时分别标记它们.

I have removed the plt.axvline(...), plt.xlabel(...) and plt.ylabel(...) out of the for loop as you only need to call it once. I've also removed the plt.legend() from the for loop for the same reason and have removed its arguments. If you supply the keyword argument label to plt.plot() then you can label your plots individually as you plot them.

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

mean = [10,12,16,22,25]
variance = [3,6,8,10,12]

x = np.linspace(0,40,1000)

for i in range(4):
    sigma = np.sqrt(variance[i])
    y = mlab.normpdf(x,mean[i],sigma)
    plt.plot(x,y, label=r'$v_{}$'.format(i+1))

plt.xlabel("X")
plt.ylabel("P(X)")        
plt.axvline(x=15, ymin=0, ymax=1,ls='--',c='black')

plt.legend()
plt.show()

这篇关于在数学模式下将变量编写为下标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆