How do I make the width of the title box span the entire plot?

后端 未结 2 1036
傲寒
傲寒 2020-11-27 18:37

consider the following pandas series s and plot

import pandas as pd
import numpy as np

s = pd.Series(np.random.lognormal(.001, .01, 100))
ax =          


        
2条回答
  •  半阙折子戏
    2020-11-27 18:59

    Instead of scaling the bounding box of the title text itself, you can create a secondary axis above the primary one and use it as a "box" for your title. As axes normally don't look as boxes, we'll switch off its axes labels and ticks, and will set the background color to black to match the OP.

    I'm using the same approach to make a secondary, matching, axis as here.

    Additionally, I've used AnchoredText to snap the title text to the axis so that it can easily be located in the center of it.

    import matplotlib.pyplot as plt 
    from matplotlib.offsetbox import AnchoredText
    from mpl_toolkits.axes_grid1 import make_axes_locatable
    import pandas as pd
    import numpy as np
    
    s = pd.Series(np.random.lognormal(.001, .01, 100))
    ax = s.cumprod().plot()
    
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("top", size="11%", pad=0)
    cax.get_xaxis().set_visible(False)
    cax.get_yaxis().set_visible(False)
    cax.set_facecolor('black')
    
    at = AnchoredText("My Log Normal Example", loc=10,
                      prop=dict(backgroundcolor='black',
                                size=12, color='white'))
    cax.add_artist(at)
    
    plt.show()
    

    Edit: for older matplotlib versions you might need to switch to cax.set_axis_bgcolor('black') when setting the background color.

提交回复
热议问题