3

I am trying to create a subplot showing different parameters 'a' and 'b', which have the units of 'MPa' and '%' respectively. In the example, I am using a separate Data-Frame which contains the information about the units. The reason for this is because the Data Frames are sourced from a Database.

I seem to keep getting the following error for parameter 'b':

ValueError: 1 b: ($%%$) ^ Expected end of text (at char 9), (line:1, col:10)

The code is as follows:-

import pandas as pd
import matplotlib.pyplot as plt

#Random Data
units = pd.DataFrame([['a', 'MPa'], ['b', '%']], index = [0,1], columns = ['Type', 'Unit'])
data = pd.DataFrame({'Val':[20,30,50,70,80,90,20,10,15,99,58],
                     'Depth':[10,20,30,40,10,20,30,40,50,100,110],
                     'Type':['a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'b', 'b','b']})

#Plot Data
fig, (ax1, ax2) = plt.subplots(1,2)
ax1_unit = units.loc[units['Type'] == 'a', 'Unit']
ax2_unit = units.loc[units['Type'] == 'b', 'Unit']

ax1.plot(data.loc[data['Type'] == 'a', 'Val'],
         data.loc[data['Type'] == 'a', 'Depth'])

ax1.set_xlabel('a: ($' + ax1_unit + '$)')

ax2.plot(data.loc[data['Type'] == 'b', 'Val'],
         data.loc[data['Type'] == 'b', 'Depth'])

ax2.set_xlabel('b: ($' + ax2_unit + '$)')

fig.show()

I think its something to do with '%' being a reserved character. I have tried replacing it with '%%' and even '%%%' as suggested in a few places, which do not work.

2
  • You mean f.show() and not fig.show(), right? Commented May 12, 2017 at 12:52
  • @Cleared. I fixed it :-) Commented May 12, 2017 at 13:09

1 Answer 1

2

Escape the percentage-sign with

'\%'

instead. That should work.

Sign up to request clarification or add additional context in comments.

2 Comments

Strangely, I did try this before and it did not work, but now it does!!. Thanks..
@MattyT. The escape is only necessary if TeX mode is enabled for your plots because % has meaning in TeX. You should not need the escape if matplotlib.rcParams['text.usetex'] is False. You must have enabled it at some point without realizing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.