Search code examples
stringpython-3.xmatplotlibstring-formattingaxis-labels

How to label y axis of a plot when the argument is a variable passed to format() function?


In running my code each time, I am making many plots whose y-axes' labels vary slightly from one plot to the next. Since my code is long, I prefer to produce all the plots with a single run such that the portion of the labels that is the same is known a priori. I am trying to use format() function in python to print label for each plot given this known value. Since I am using Latex notations inside my axes' labels, I don't know how to resolve the issue.

z_value = 0.
ax.set_ylabel(r'$\frac {dN_{{abs.}}} {d [\log(m_{{sub}})]} (m_{{sub}}, z={:.1f})$'.format(z_value))

Error:

ax.set_ylabel(r'$\frac {dN_{{abs.}}} {d [\log(m_{{sub}})]} (m_{{sub}}, z={:.1f})$'.format(z_value))

ValueError: unexpected '{' in field name


Solution

  • You will need to double each { and } which is not being used as formatting indicator. You also need to escape the backslash:

    >>> x=2.5
    >>> print('Dies ist {{{}x eine Variable'.format(x))
    Dies ist {2.5x eine Variable
    
    >>> print('$\\frac {{dN_{{abs.}}}} {{d [\\log(m_{{sub}})]}} (m_{{{{sub}}}}, z={:.1f})$'.format(x))
    $\frac {dN_{abs.}} {d [\log(m_{sub})]} (m_{{sub}}, z=2.5)$