ZK Zhao
ZK Zhao

Reputation: 21573

Set x and y label in one line

If I want to set the x, y label for each axis, I have to do something like this:

import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('This is y label')
plt.xlabel('This is x label')
plt.show()

I need to set xlabel, ylabel seperately.

I'm wondering if there is any syntax sugur that I can do something like:

plt.label('x label', 'y label')

so the code looks more compact?

Or how can I make any custom function to do this?

Upvotes: 5

Views: 6847

Answers (2)

Oliver W.
Oliver W.

Reputation: 13459

Once you start using the object oriented model of matplotlib more often, you'll be able to add all relevant parameters of an axes as keywords to the functions that make these axes.

A simple example:

fig = plt.figure()
ax = fig.add_subplot(111, xlabel="time", ylabel="money")

A longer example:

fig1 = plt.figure(figsize=(10,8))
ax1 = fig1.add_axes((0.1, 0.1, 0.8, 0.8), # full positional control
    frameon=True,                         # display frame boundary
    aspect='equal',                       # set aspect ratio upon creation
    adjustable='box',                     # what part of the axes can change to meet the aspect ratio requirement?
    xticks=[0.1, 1.2, 10],                
    xlabel='voltage (V)',
    xlim=(0.05, 10.05),
    yticks=[0, 10],
    ylabel='current (µA)',
    ylim=(0, 2))

Following up on the received comment, you can also make use of the "property batch setter" ax.set, which is a nice little matplotlib convenience function.

plt.close('all')
plt.plot([1,2,3], [4, 7, 1])
plt.gca().set(xlabel='x', ylabel='y')

Upvotes: 8

panadestein
panadestein

Reputation: 1291

Maybe this can help you

import matplotlib.pyplot as plt

def grap_label(g, lx='',ly=''):
    plt.xlabel(lx)
    plt.ylabel(ly)
    plt.show()

grap_label(plt.plot([1,2,3,4]), 'This is x label','This is y label')

Upvotes: 1

Related Questions