Reputation: 5730
When I run this function,
def plot_data(df, title="", xlabel="", ylabel="", figsize=(12, 8), save_figure=False):
from matplotlib.font_manager import FontProperties
fontP = FontProperties()
fontP.set_size('small')
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.legend(bbox_to_anchor=(1,1), loc='upper left', prop=fontP)
plt.grid()
df.plot()
plt.show()
if save_figure:
plt.savefig(title)
the result looks like this:
I don't understand why two figure objects come up. And it looks like legend
, grid
are not applied appropriately...
Also, I want to clearly know about "when figure object created" or "how can I create just one figure object without confusion" kind of thing. Is there any good tutorial for this?
Upvotes: 1
Views: 106
Reputation: 152657
That's because DataFrame.plot
, by default, doesn't use the current active figure but creates a new figure. But that's just default behavior - You can override it by explicitly passing the active axes (ax
argument) in:
df.plot(ax=plt.gca()) # gca stands for "get currently axes" instance
Or you can simply put the df.plot
command at the top because (unlike df.plot
) most plt
functions modify the current active figure and some plt
commands (e.g. legend
) even won't work if there's no "plot" yet:
def plot_data(df, title="", xlabel="", ylabel="", figsize=(12, 8), save_figure=False):
# Moved to the top
df.plot()
from matplotlib.font_manager import FontProperties
fontP = FontProperties()
fontP.set_size('small')
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.legend(bbox_to_anchor=(1,1), loc='upper left', prop=fontP)
plt.grid()
plt.show()
if save_figure:
plt.savefig(title)
Upvotes: 3