简体   繁体   中英

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

Question

  • I have used the secondary_y argument in pd.DataFrame.plot().
  • While trying to change the fontsize of legends by .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.
  • This problem (having only 1 column name in the legend) does not take place when I did not use secondary_y argument.
  • I want all the column names in my dataframe to be printed in the legend, and change the fontsize of the legend even when I use secondary_y while plotting dataframe.

Example

  • The following example with secondary_y shows only 1 column name A , when I have actually 2 columns, which are A and B .
  • The fontsize of the legend is changed, but only for 1 column name.
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")

在此处输入图像描述

  • When I do not use 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")

在此处输入图像描述

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: 在此处输入图像描述

this is a somewhat late response, but something that worked for me was simply setting plt.legend(fontsize = wanted_fontsize) after the plot function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM