为什么 ax2 在 matplotlib 子图中覆盖 ax1 的 y 轴?

Why is ax2 writing over ax1's y-axis in matplotlib subplots?

我正在尝试将之前的双胞胎图表代码更改为子图。我不熟悉子图,无法弄清楚为什么 ax2 标签会覆盖 ax1 的 y 轴标签。

目标是让 ax2 中的标签靠右。

当我运行带有标签的代码时:

当我移除标签时:

import matplotlib
#matplotlib.use('Agg')
from matplotlib import pyplot as plt
import xlsxwriter as xl
import numpy as np
import yfinance as yf
import pandas as pd 
from datetime import date
#from dateutil.relativedelta import relativedelta
import mplfinance as mpf 
import pandas_datareader 
from pandas_datareader import data as pdr
yf.pdr_override()
import numpy as np
from textwrap import wrap

Individualreport = "C:\Users\Ashley\FromPython1.xlsx"

READ = "C:\Users\Ashley\Biotech Example.xlsx"

Ticklist = pd.read_excel(READ,sheet_name='Tickers', header=None)
stocks = Ticklist.values.ravel()

writer = pd.ExcelWriter(Individualreport, engine='xlsxwriter')

#pipeline
row_pipe = 9
col_pipe = 0
#misc
row_tick = 0
col_tick = 0
#graph
short_sma = 20
mid_sma = 50
long_sma = 100
image_row = 24
image_col = 0
#overview
row_over = 3
col_over = 0
row_overnumb = 6
col_overnumb = 0
tit_row = 0
tit_col = 0

page_len = 47


OverviewReport = pd.read_excel(READ, sheet_name='Overview', header=None, skiprows=1)
overviewcolstitle = pd.read_excel(READ, sheet_name='Overview', header=None,nrows=1).values[0]
OverviewReport.columns = overviewcolstitle

title = ['Company','Ticker']
tit = OverviewReport[title]
cols1= ['Ticker','Category','Focus','Class']#,'Pipeline Score']
oo = OverviewReport[cols1]
cols2= ['M Cap (mil)','EV','Cash (mil)','EV/  Cash','Rev TTM','Price','% Ch Price\n1 W','% Ch Price\n12 W','% Ch Price\nYTD']#, 'Cash/ Share']
nn = OverviewReport[cols2]
print(overviewcolstitle)

PipelineData = pd.read_excel(READ, sheet_name='Pipeline', header=None, index_col=None)
pipelinecolstitle = pd.read_excel(READ, sheet_name='Pipeline', header=None,nrows=1).values[0]
PipelineData.columns = pipelinecolstitle

for i in stocks:

    #write ticker
    s = Ticklist.loc[(Ticklist[0]==i)]
    print(s)
    s.to_excel(writer, sheet_name='Sheet1', startrow= row_tick, startcol=col_tick, header=False, index=False)
    row_tick += page_len

    wb = writer.book
    ws = writer.sheets['Sheet1']

    
    #WRITE PIPELINE
    ppp = PipelineData['Ticker']

    ccc = PipelineData['Catalyst']
    cc = ccc.loc[ppp==i]
    label = cc+str("      ")
    #label = [ '\n'.join(wrap(l, 50)) for l in label ]
    
    dd = PipelineData['Drug']
    drugs = dd.loc[ppp==i]
    drugs = drugs+str("     ")
    #drugs = [ '\n'.join(wrap(drugs, 35)) for d in drugs ]


    pp = PipelineData['Phase']
    p = pp.loc[ppp==i]

    disdis = PipelineData['Disease']
    dis = disdis.loc[ppp==i]
     
     
    fuk, axs = plt.subplots(1, 2, sharex='col', sharey='row',
                    gridspec_kw={'hspace': 0, 'wspace': 0})
    (ax1, ax2) = axs
    #fuk = plt.figure(figsize=(11,6.3))
    #ax1 = fuk.add_subplot()
    #ax2 = ax1.twinx()

    width = 0.7 # the width of the bars
    ind = np.arange(len(p))  # the x locations for the groups
    ax1.barh(ind, p, width, color="#67a362", align='edge')
    ax1.set_yticks(ind+width/2)
    ax1.set_yticklabels(drugs, minor=False, fontname= 'Times New Roman', wrap=True)
    ax1.set_ylabel('Drug', fontname= 'Times New Roman', wrap=True)
    ax1.set_xmargin(1)
    ax1.autoscale_view()
    
    ax2.set_ylim(ax1.get_ylim())
    ax1.set_yticks(np.arange(len(label)) + width/2)
    ax2.set_yticklabels(label,horizontalalignment = "right", fontname='Times New Roman', wrap=True) #CAN CHANGE HORIZONTALALLIGNMENT HERE 
    #ax1.spines['right'].set_color('None')
    #ax2.autoscale_view(scalex=False)
    #ax2.spines['right'].set_color('None')
    
    #ax1.xticks(np.arange(5),('Pre-clinical','Phase I','Phase II','Phase III', 'Approved'), fontname='Times New Roman', wrap=True)
    plt.rcParams['ytick.major.pad']=-12
    plt.rcParams['axes.grid'] = False
    plt.rcParams['font.family']='serif'
    plt.rcParams['font.size']=12.5
    ax1.grid(False)
    ax2.grid(False)
    ax1.set_facecolor('w')
    ax2.set_facecolor('w')

    for bar, disease in zip(ax1.patches, dis):
        ax1.text(0.1, bar.get_y()+bar.get_height()/2, disease, color = 'black', ha = 'left', va = 'center')

    #fuk.suptitle(i)
    fuk.savefig(str(i)+'newpipe.png', bbox_inches=None, wrap=True)
    ws.insert_image(row_pipe,col_pipe,str(i)+'newpipe.png',{'x_scale':.56, 'y_scale':.56})
    row_pipe += page_len
    
    
    plt.show()





# Some example data to display
#x = np.linspace(0, 2 * np.pi, 400)
#y = np.sin(x ** 2)
#for i in stocks:
 #    fig, axs = plt.subplots(1, 2, sharex='col', sharey='row',
  #                      gridspec_kw={'hspace': 0, 'wspace': 0})
   #  (ax1, ax2) = axs
    # fig.suptitle('Sharing x per column, y per row')
     #ax1.barh(0, 4)
     #ax2.plot(x, y**2, 'tab:orange')

     #for ax in axs.flat:
      #    ax.label_outer()
     #plt.show()

试试这个:

ax2.yaxis.set_label_position('right')
ax2.yaxis.tick_right()

就在(ax1, ax2) = axs

之后