Search code examples
pythonmatplotlibaxis-labels

Adding multiple subscripted characters in matplotlib axis labels using format


I'm trying to add some subscripts to the y-label of a figure, and have it done using format so that I don't have to manualy make multiple figures. Since matplotlib allows for TeX formatting, this is quite easy, but the brackets for having multiple characters for sub- or superscript overlaps with format. The code I'm using is

fig, ax = plt.subplots()
ax.plot(a,real_int, label='real int')
ax.plot(a,EM_int_sim, label='EM int')
ax.set_xlabel('t')
format_list = [l,j]
ax.set_ylabel(r"$\phi_{}$".format(*[l,j]))
ax.set_title("Offspring intensities")
ax.legend()

Normally in TeX formatting I'd use \phi_{lj} to write the characters, but format also uses the curly brackets. The above code only gives l in the subscript (which I expected), but I've also tried \phi_{{}} which doesn't give any characters, \phi_{}{} which only subscripts l but not j and \phi_{}_{} which gave the longes error message I've ever seen. Any ideas?


Solution

  • Alright, so if you switch your method for string insertion it works. Also i convert the list of ints you want to insert to a string to make it work. But you could also do multiple insertions into the curly brackets by doing different %s/%d/f..etc

    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots(dpi=300)
    ax.set_xlabel('t')
    format_list = [0,1]
    
    string_list=",".join([str(val) for val in format_list])
    
    ax.set_ylabel(r"$\phi_{%s}$" % string_list)
    ax.set_title("Offspring intensities")
    ax.legend()