4

I am trying to automatically label the x-axis of a Matplotlib plot in Python2.7 with a chemical formula that has numbers as subscripts, without italics.

Here is a code to show this:

import numpy as np
import pylab as plt

x = np.array([1,2,3,4])
y = np.array([1,2,3,4])

chem_list = ['H2O','CO2','X7Z4']

for j, elem in enumerate(chem_list):
    plt.plot(x,y)
    plt.xlabel(chem_list[j])
    plt.legend(loc=1)
    plt.show()

The x-axis labels come from a list. Each item in the list is a label and I need to use it as the text in the label.

This method works, however, the text is italicized and I need to avoid italic text. Another post that produces italic text: here.

Example of my question:

For the first iteration of the loop, I would like to use H2O ax the x-axis label, but I do not want it to be italicized.

Is there a way to do this in Python?

Community
  • 1
  • 1
edesz
  • 11,756
  • 22
  • 75
  • 123

1 Answers1

5

Based on the documentation (http://matplotlib.org/users/mathtext.html), you can use \mathregular{...} to use regular text within a mathtext expression. For you case, for example, you would write:

chem_list = ['$\mathregular{H_2O}$','$\mathregular{CO_2}$','$\mathregular{X_7Z_4}$']
Jean-Sébastien
  • 2,649
  • 1
  • 16
  • 21
  • Thanks. That would work. However, to use this, I would need to first replace H20 by H_20 or X_7Z_4. Is there a way to search for '2' and, if it is found, replace it by '_2'? Or in the case of X_7Z_4, is there a way to automatically replace 7 and 4 by _7 and _4? – edesz Aug 15 '15 at 05:03
  • Got it working. Found an answer [here](http://ubuntuforums.org/showthread.php?t=986061). I used the following: `chem_list = [re.sub("([0-9])", "_\\1", k) for k in chem_list]` and then this string concatenation to assemble your code: `chem_list_new = ['$\mathregular{'+list_k+'}$' for list_k in chem_list]`.Many thanks for your help with this post - I was having real trouble finding a way to avoid the italics, but your method works. – edesz Aug 15 '15 at 05:32
  • @WR Great. I'm sorry that I did not catch the "automatic" part of your question. Do you mind if I add to my answer the part of solution you gave in the comment above for the sake of completeness? – Jean-Sébastien Aug 15 '15 at 05:47
  • No problem. Sure go ahead. That would be great. This italic problem was a real concern for me - thanks for your feedback here. – edesz Aug 15 '15 at 23:42