Eiffelbear
Eiffelbear

Reputation: 428

How to change the legend font size of pd.DataFrame.plot() when `secondary_y` is used?

Question

Example

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")

enter image description here

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")

enter image description here

Upvotes: 3

Views: 5961

Answers (3)

francoua
francoua

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

BenjaminLi
BenjaminLi

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

Renaud
Renaud

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()

result: enter image description here

Upvotes: 1

Related Questions