I would like to know why depending on how you call plt.plot()
on an ax
this ax
may or may not be able to be modified downstream. Is this a bug in matplotlib
or am I misunderstanding something? An example which illustrates the issue is shown below.
I am attempting to modify the legend location downstream of a plotting function call, similar to as discussed here. For whatever reason this seams to be dependent on how I call ax.plot
. Here are two examples illustrating the issue
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def myplot(df, ax, loop_cols):
if loop_cols:
for col in df.columns:
ax.plot(df.loc[:, col])
else:
ax.plot(df)
ax.legend(df.columns)
return ax
This just amounts to calling ax.plot()
repeatedly on the pd.Series
, or calling it once on the pd.DataFrame
. However depending on how this is called, it results in the inability to later modify the legend, as shown below.
df = pd.DataFrame(np.random.randn(100, 3)).cumsum()
fig = plt.figure()
ax = fig.gca()
myplot(df, ax, loop_cols=True)
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
plt.show()
Chart legend properly set to right side
fig = plt.figure()
ax = fig.gca()
myplot(df, ax, loop_cols=False)
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
plt.show()
Chart legend not set to appropriate location
This is with matplotlib
version 2.1.0