I am trying to write a user-defined function to add titles and labels to the syntax for a graph. This is what I am trying to do:
def mytitles(title,xvar,yvar):
in other to achieve this:
mytitles('title_name', 'xvar_name', 'yvar_name')
I am trying to write a user-defined function to add titles and labels to the syntax for a graph. This is what I am trying to do:
def mytitles(title,xvar,yvar):
in other to achieve this:
mytitles('title_name', 'xvar_name', 'yvar_name')
if you are using matplotlib
, you need tou use:
ax.set_xlabel(label)
for x axis titleax.set_ylabel(label)
for y axis titleax.set_title(title)
for figure titleFirst you ll need to get either a figure or an ax object. Your function will act on them by calling the above methods. For example, ill plot a simple plot:
import matplotlib.pyplot as plt
import numpy as np
x = 2*np.arange(0, 3, .05)
y = np.sin(x)
figure, ax = plt.subplots(figsize=(5,5))
ax.plot(x,y)
If it is generated, like your case, with pandas
, you'll need to do something similar to this:
figure = mydf.plot(x='x', y='y')
In my case mydf
is created like this:
x = 2*np.arange(0, 3, .05)
y = np.sin(x)
mydf = pd.DataFrame({'x':x, 'y':y })
Here, there only one axes since I want to plot only one plot in my figure. To get axes from figure object, I can do figure.axes
and it contains a list of figure axes.
I can then define this function:
def add_text(fig, title, xlabel, ylabel):
fig.axes[0].set_xlabel(xlabel)
fig.axes[0].set_ylabel(ylabel)
fig.axes[0].set_title(title)
return fig
So to add title, xlabel and ylabel to my original figure, I can run this:
add_text(figure, 'mytile', 'myxlabel', 'myylabel')
Here, you can find more details about what are matplotlib objects: Understanding matplotlib: plt, figure, ax(arr)?
You might use this function
plt.title(f'$D_q$ curve at the parameter q={q}')