简体   繁体   中英

Python 3 matplotlib add a watermark with multiple scale axis

In python 3, i am trying to add watermark with multiple scale axis in the following pandas data frame

index,as_of_date,Total_10bn,close
0,2020-08-05,620.55975367473,332.11
1,2020-08-12,621.9414641848599,337.44
2,2020-08-19,628.88298116372,337.23
3,2020-08-26,627.26943375402,347.57
4,2020-09-02,630.01703674403,357.7
5,2020-09-09,630.70673674269,339.79
6,2020-09-16,637.50390815142,338.82

I can make the multiple scale works

df_soma_spy=pd.read_csv('df_soma_spy.csv')

print(df_soma_spy)

# create figure and axis objects with subplots()

fig,ax = plt.subplots()

plt.xticks(rotation=90)

ax.plot(df_soma_spy.as_of_date, df_soma_spy.Total_10bn, color="red") ## , marker="o"

# set x-axis label

ax.set_xlabel("Date", fontsize=12)

# set y-axis label

ax.set_ylabel("Fed SOMA ($10bn)",color="red",fontsize=14)

plt.grid(True, axis='both', which='both')

# twin object for two different y-axis on the sample plot

ax2=ax.twinx()

# make a plot with different y-axis using second axis object

ax2.plot(df_soma_spy.as_of_date, df_soma_spy["close"], color="black") ## , marker="o"

ax2.set_ylabel("$SPY Price",color="black",fontsize=14)


plt.title('Federal Reserves SOMA Total vs $SPY')

plt.show()

# save the plot as a file
fig.savefig('soma_spy.png',
            format='jpeg',
            dpi=300,
            bbox_inches='tight')

在此处输入图像描述

Now I am trying to add a logo behind the picture. But no matter how I try, it will mess up one of the axis.

For example

import matplotlib.image as image

im = image.imread('xxx.png')

myaximage = ax.imshow(im, aspect='auto', extent=(0.1,0.1,0.1,0.1), alpha=0.5, zorder=-1)

In this case, the logo doesn't show up and the red axis is totally messed up.

在此处输入图像描述

There are some other solutions but none of them seems to work.

Scale image in matplotlib without changing the axis

Matplotlib automate placement of watermark

Scale image in matplotlib without changing the axis

Any thoughts? Thank you!

Instead of ax.imshow(), you can use fig.figimage() as shown below and described here . Just insert the following two lines in your code:

logo = image.imread(fname='logo.png')
fig.figimage(logo,alpha= 0.1)

Using the partial data you provided, here is the saved image:

在此处输入图像描述

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