3

How to set the x-label and y-label in a matplotlib-plot passing them as an parameter to the plot() function.

Basically I want to do something like this:

def plot_something(data, plot_conf):
    data.plot(**plot_conf)
    ...do some other stuff...

plot_conf = {'title': 'Blabla', 'xlabel':'Time (s)', 'ylabel': 'Speed (m/s)'}
plot_something(data,plot_conf)

I would prefer not to use any additional function calls, like xlabel()

3
  • See the documentation of the pyplot.plot for valid kwargs. You can't pass xlabel, ylabel and title as arguments to the plot() method, as those are properties of Axes instances. The plot() method returns a Line2D instance. IMO the easiest and most intuitive way to achieve this would be to change your plot_something() function to actually use additional function calls. Commented Jun 8, 2013 at 16:13
  • A simplified explanation as to why you can not do this readily: You can have several calls to the plot() method for each Axes object (e.g. plot two or more different lines in same subplot). If each of these method calls were to set the title, xlabel and ylabel of the Axes, everything would get pretty messy pretty fast! Also, this wouldn't be as intuitive and object-oriented as it currently is. Commented Jun 8, 2013 at 16:36
  • @sjosund just to remind you can upvote the answer ;) Commented Jun 26, 2015 at 9:54

1 Answer 1

4

As @nordev already explained, you cannot pass through plot() the axis label, but inside your function you can get the active figure and then set the axis labels like the example below:

import matplotlib.pyplot as plt
def plot_something(x, y, **kwargs):
    title  = kwargs.pop( 'title'  )
    xlabel = kwargs.pop( 'xlabel' )
    ylabel = kwargs.pop( 'ylabel' )
    plt.figure()
    plt.plot(x, y, **kwargs)
    fig = plt.gcf()
    for axis in fig.axes:
        axis.set_title( title )
        axis.xaxis.set_label_text( xlabel )
        axis.yaxis.set_label_text( ylabel )
    return axis


plot_conf = {'title': 'Blabla', 'xlabel':'Time (s)', 'ylabel': 'Speed (m/s)'}
x = [1.,2.,3.]
y = [1.,4.,9.]
axis = plot_something(x=x,y=y, **plot_conf)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the code. The axis labels part didn't work for me in first go. I made it work by changing set_label to set_label_text
@Atlas7 thanks for the comment, I updated the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.