Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 765
BillyJo_rambler Avatar asked Jan 30 '26 14:01

BillyJo_rambler


1 Answers

Escape the percentage-sign with

'\%'

instead. That should work.

like image 114
Cleared Avatar answered Feb 02 '26 04:02

Cleared



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!