X Tutup
Skip to content

Simpler code for common plot setting (e.g. legend, lable, title, figsize)? #8370

@0xzkzhao

Description

@0xzkzhao

As I use matplotlib more and more, I find setting the figure cumbersome, for example

x = [1,2,3,4,5]
y = [5,2,6,7,2]
plot(x, y, '-', label='test')
ax = plt.gca()
ax.set_title('This is my title')
ax.set_xlabel('X name')
ax.set_ylabel('Y name')
ax.legend()
plt.gcf().set_size_inches(4,4)

enter image description here

For I make a sufficient plot, too many lines of code are simply about the figure configuration.

I want to know, if there are simple ways to do this? For example, in pandas we can do

df['my_column'].plot(kind='bar', figsize=(20,4), ....)

Currently, I solve this problem by define a plt_configure() function,

enter image description here

The code looks like

def plt_configure(ax=None, xlabel=None, ylabel=None, title='', legend=False, tight=False, figsize=False, no_axis=False):
    if ax == None :
        ax=plt.gca()
        plt.suptitle(title)
    else:
        ax.set_title(title)

    if xlabel:
        ax.set_xlabel(xlabel)
    if ylabel:
        ax.set_ylabel(ylabel)
    if legend:
        if isinstance(legend, dict):
            ax.legend(**legend)
        else:
            ax.legend()
    if tight:
        if tight == 'xtight' or tight == 'x':
            ax.autoscale(enable=True, axis='x', tight=True)
        elif tight == 'ytight':
            ax.autoscale(enable=True, axis='y', tight=True)
        else:
            ax.axis('tight')
    if figsize:
        plt.gcf().set_size_inches(figsize)
    if no_axis:
        plt.gca().axis('off')
        legend = ax.legend()
        if legend:
            legend.remove()

Note: this is also asked at http://stackoverflow.com/questions/42976996/matplotlib-simpler-code-for-common-plot-setting-such-as-legend-lable-title

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      X Tutup