Home > Software design >  Split the string into lines from the nth delimiter as the title of the plot
Split the string into lines from the nth delimiter as the title of the plot

Time:11-24

For the dictionary d, I extracted the combination of key-value pairs as the title of matplotlib plot, but assuming that string res is too long, I want to split res from the second comma into two lines as the title of the plot, how should I do it? Thanks.

d = {'lag(0)_pred': 0.83,
'lag(1)_pred': 0.51,
'lag(2)_pred': 0.17,
'lag(3)_pred': 0.52
}

out = [f'{key}: {d[key]:.2f}' for key in d]
res = ", ".join(out)
res

Out:

'lag(0)_pred: 0.83, lag(1)_pred: 0.51, lag(2)_pred: 0.17, lag(3)_pred: 0.52'

Code of the plot:

import matplotlib.pyplot as plt

x = [1, 2, 3]
y = [4, 5, 6]
plt.figure(figsize=(8, 5))
plt.plot(x, y)
# set title
plt.title(f"{res}", loc='center', wrap=True)
plt.show()

Out:

enter image description here

The expected result:

enter image description here

CodePudding user response:

The code following works:

Option 1:

import matplotlib.pyplot as plt

n = 2
groups = res.split(', ')
result = ', '.join(groups[:n]), ', '.join(groups[n:])

x = [1, 2, 3, 9]
y = [4, 5, 6, 9]
plt.figure(figsize=(8, 5))
plt.plot(x, y)
# set title
plt.title(f"{result[0]}\n{result[1]}", loc='center', wrap=True)
plt.show()

Out:

enter image description here

Option 2:

import re

n = 1
occerence = [m.start() for m in re.finditer(', ', res)]
result = [res[:occerence[n]], res[occerence[n] 1:]]
result

x = [1, 2, 3, 9]
y = [4, 5, 6, 9]
plt.figure(figsize=(8, 5))
plt.plot(x, y)
# set title
plt.title(f"{result[0]}\n{result[1]}", loc='center', wrap=True)
plt.show()

Out:

enter image description here

Option 3, best and simplest solution provided by @JohanC:

d = {'lag(0)_pred': 0.83, 
'lag(1)_pred': 0.51, 
'lag(2)_pred': 0.17, 
'lag(3)_pred': 0.52
}

out = [f'{key}: {d[key]:.2f}' for key in d]
res = ", ".join(out[:2])   "\n"   ", ".join(out[2:])

x = [1, 2, 3, 9]
y = [4, 5, 6, 9]
plt.figure(figsize=(8, 5))
plt.plot(x, y)
# set title
plt.title(f"{res}", loc='center', wrap=True)
plt.show()

Out:

enter image description here

  • Related