BillyJo_rambler
BillyJo_rambler

Reputation: 583

Issues using '%' for a Plot label in Matplotlib

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.

Upvotes: 3

Views: 1074

Answers (1)

Cleared
Cleared

Reputation: 2590

Escape the percentage-sign with

'\%'

instead. That should work.

Upvotes: 2

Related Questions