Reputation: 428
secondary_y
argument in pd.DataFrame.plot()..legend(fontsize=20)
, I ended up having only 1 column name in the legend when I actually have 2 columns to be printed on the legend.secondary_y
argument.secondary_y
while plotting dataframe.secondary_y
shows only 1 column name A
, when I have actually 2 columns, which are A
and B
.import pandas as pd
import numpy as np
np.random.seed(42)
df = pd.DataFrame(np.random.randn(24*3, 2),
index=pd.date_range('1/1/2019', periods=24*3, freq='h'))
df.columns = ['A', 'B']
df.plot(secondary_y = ["B"], figsize=(12,5)).legend(fontsize=20, loc="upper right")
secondary_y
, then legend shows both of the 2 columns A
and B
.import pandas as pd
import numpy as np
np.random.seed(42)
df = pd.DataFrame(np.random.randn(24*3, 2),
index=pd.date_range('1/1/2019', periods=24*3, freq='h'))
df.columns = ['A', 'B']
df.plot(figsize=(12,5)).legend(fontsize=20, loc="upper right")
Upvotes: 3
Views: 5961
Reputation: 13
I managed to kind of solve the problem, but my legend is divided into two parts :
fig, ax = plt.subplots()
# your code with your plots
ax.legend(['A'], fontsize=15)
ax.right_ax.legend(['B'], fontsize=15)
Upvotes: 0
Reputation: 73
this is a somewhat late response, but something that worked for me was simply setting plt.legend(fontsize = wanted_fontsize)
after the plot function.
Upvotes: 4
Reputation: 2819
To manage to customize it you have to create your graph with subplots function of Matplotlib:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(42)
df = pd.DataFrame(np.random.randn(24*3, 2),
index=pd.date_range('1/1/2019', periods=24*3, freq='h'))
df.columns = ['A', 'B']
#define colors to use
col1 = 'steelblue'
col2 = 'red'
#define subplots
fig,ax = plt.subplots()
#add first line to plot
lns1=ax.plot(df.index,df['A'], color=col1)
#add x-axis label
ax.set_xlabel('dates', fontsize=14)
#add y-axis label
ax.set_ylabel('A', color=col1, fontsize=16)
#define second y-axis that shares x-axis with current plot
ax2 = ax.twinx()
#add second line to plot
lns2=ax2.plot(df.index,df['B'], color=col2)
#add second y-axis label
ax2.set_ylabel('B', color=col2, fontsize=16)
#legend
ax.legend(lns1+lns2,['A','B'],loc="upper right",fontsize=20)
#another solution is to create legend for fig,:
#fig.legend(['A','B'],loc="upper right")
plt.show()
Upvotes: 1