python - 如何修复seaborn热图上的重叠yaxis
问题描述
当我保存图像时,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')
我的结果图片如下所示:
解决方案
在您sns.heatmap
尝试添加关键字参数的调用中square=True
推荐阅读
- c++ - 将指针数组传递给 3D 数组:访问冲突异常 (C++)
- c - CreateProcessA %appdata%
- javascript - 检测 Chrome 移动 Android 浏览器上的选项卡关闭
- c++ - 无法绑定可变参数函数并保存到 std::function
- python - 在 Jupyterhub 中使用虚拟环境管理开发/部署包
- javascript - 如何使此功能按预期工作?
- three.js - 如何在不使用 JSONLoader 的情况下从 JSON 对象创建 three.js 几何
- r - 按 R 中的值的总和进行十进制
- c# - 在调用异步代码时始终考虑 AggregateExceptions 中的多个异常是否有意义?
- elasticsearch - 融合弹性搜索接收器正则表达式分配给所有主题并发送到索引