0

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')
yashaswi k
  • 668
  • 7
  • 17

2 Answers2

0

if you are using matplotlib, you need tou use:

  • ax.set_xlabel(label) for x axis title
  • ax.set_ylabel(label) for y axis title
  • ax.set_title(title) for figure title

First 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)?

inarighas
  • 720
  • 5
  • 24
0

You might use this function

plt.title(f'$D_q$ curve at the parameter q={q}')

  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 03 '23 at 07:02