如何修复seaborn热图上的重叠yaxis

2024-04-24 01:16:04 发布

您现在位置:Python中文网/ 问答频道 /正文

保存图像时,seaborn热图上的y轴重叠。如何使整个图像展开一点,使每个细胞看起来像一个正方形

如果导出的图片很长就可以了

我试图调整figsize,但保存的图片没有任何区别。有没有其他方法来调整呢

我的代码是:

import seaborn as sns
import pandas as pd
import datetime as dt
import matplotlib.pyplot as plt
import yfinance as yf
#import xlsxwriter
#====================================================
prev=150
endDate=dt.datetime.today().date()
sDate=endDate-pd.to_timedelta(prev,unit='d')
#--------------------------------------------------------------
def get_price(tickers,roll_num=20): #input is a list or Series
    result=pd.DataFrame()
    pic=pd.DataFrame()
    for i in tickers:
        try:
            df=pd.DataFrame()                
            df['Adj Close']=yf.download(i,sDate,endDate)['Adj Close']
            df['MA']=df['Adj Close'].rolling(roll_num).mean()
            df.sort_values(ascending=False,inplace=True,by="Date")  # sometimes error
            df['Higher?']=df['Adj Close']>df['MA']
            df['Higher?']=df['Higher?'].astype(int)
            result[str(i)]=df['Higher?']
            
        except Exception as ex:  # no date column
            print('Ticker', i, 'ERROR', ex)
            print(df)
    pic[tickers.name]=(result.sum(axis=1)/len(result.columns)*100).astype(int) 
    pic.name=tickers.name   
    pic.drop(pic.tail(roll_num-1).index,inplace=True)
    return pic
#--------------------------------------------------------------
test=pd.Series(['A','TSLA','KO','T','aapl','nke'])
test=test.str.replace('.','-')
test.name='I am test'
a=get_price(test)
print(a)
#=============================================================================

base_url = "http://www.sectorspdr.com/sectorspdr/IDCO.Client.Spdrs.Holdings/Export/ExportExcel?symbol="

data = {                    
    'Ticker' :      [ 'XLC','XLY','XLP','XLE','XLF','XLV','XLI','XLB','XLRE','XLK','XLU' ]          
,   'Name' :    [ 'Communication Services','Consumer Discretionary','Consumer Staples','Energy','Financials','Health Care','Industrials','Materials','Real Estate','Technology','Utilities' ]           
}                   

spdr_df = pd.DataFrame(data)     

print(spdr_df)

#-------------------------------------------------------------------
final_product=[]


for i, row in spdr_df.iterrows():
    url =  base_url + row['Ticker']
    df_url = pd.read_excel(url)
    header = df_url.iloc[0]
    holdings_df = df_url[1:]
    holdings_df.set_axis(header, axis='columns', inplace=True)
    holdings_df=holdings_df['Symbol'].str.replace('.','-')
    holdings_df.name=row.Name
    final_product.append(get_price(holdings_df))
    
    

final_product=pd.concat(final_product,axis=1)
final_product['Sum']=final_product.sum(axis=1)
final_product.index=final_product.index.strftime('%Y-%m-%d')

#final product is the targeted dataframe on build heatmap on

column_labels = final_product.columns[:-1]
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(10, 60),
                               gridspec_kw={'width_ratios': [10, 1], 'wspace': 0.02, 'bottom': 0.14})
cmap = sns.diverging_palette(20, 145)
sns.heatmap(final_product[final_product.columns[:-1]], cmap=cmap, vmin=0, vmax=100, annot=True, fmt='.0f', annot_kws={'fontsize': 10},
            lw=0.6, xticklabels=column_labels, cbar=False, ax=ax1)
sns.heatmap(final_product[final_product.columns[-1:]], cmap=cmap, vmin=0, vmax=1100, annot=True, fmt='.0f', annot_kws={'fontsize': 10},
            lw=0.6, yticklabels=[], cbar=False, ax=ax2)
ax2.set_ylabel('')
ax2.tick_params(axis='x', labelrotation=90)
ax1.xaxis.tick_top()
ax1.xaxis.set_label_position('top')
ax1.tick_params(axis='x', labelrotation=45)
plt.savefig('heatmap.png')

我的结果图片如下所示:

enter image description here


Tags: columnsnametestimporttrueurldfas