python - 如何根据绘图的 y 值调整太阳图高度
问题描述
我想根据 KDE 图的最大出现 y 值选择子图的高度(以便在最后一个子图中仍显示整个 KDE 图)。那么如何调整绘制四分位数的公式(ax[i-1].axvline(quatrilesx[k],.....])?为什么这些线现在不再可见?
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.ticker import NullFormatter
import numpy as np
import random
def plotverweildauernwithuG(df):
def rand_float_range(start, end):
return random.random() * (end - start) + start
def find_nearest(array, value):
array = np.asarray(array)
idx = (np.abs(array - value)).argmin()
return idx
df=df[df['method']=='data']
df['years']=df['years'].astype('float64')
sns.set()
#sharex=True: x-Achse für alle Subplots geteilt
#fig,ax= plt.subplots(): tuple containing figure and axes object
fig, ax = plt.subplots(nrows=df['cs'].max(), sharex=True)
nrows=len(ax)
ax[df['cs'].max()-1].set_xlabel('Verweildauer in Jahren')
s=[(df["cs"] == t).sum() for t in range(1, df['cs'].max()+1)]
s.insert(0, 0)
print(s)
h=0
for i in range(1, df['cs'].max()+1):
#get quartiles
quatrilesx = [df[df['cs']==i]["years"].astype(float).describe()['25%'],df[df['cs']==i]["years"].astype(float).describe()['50%'], df[df['cs']==i]["years"].astype(float).describe()['75%']]
verweildauer_i = df[df['cs'] == i]['years']
cs_bandwith_i = df[df['cs'] == i]['cs_bandwith']
color_i=df[df['cs'] == i]['uGW']
verweildauer_i_nugw = df[(df['cs'] == i) & (df['uGW']==False)]['years']
cs_bandwith_i_nugw = df[(df['cs'] == i) & (df['uGW']==False)]['cs_bandwith']
verweildauer_i_ugw = df[(df['cs'] == i) & (df['uGW']==True)]['years']
cs_bandwith_i_ugw = df[(df['cs'] == i) & (df['uGW']==True)]['cs_bandwith']
#width=(10*nrows)/3
#height=(7*nrows)/3
#fig.set_size_inches(width,height)
#plt.subplots_adjust(hspace=0)
ax[i-1].scatter(verweildauer_i_nugw, cs_bandwith_i_nugw-i-0.5, c="blue", label = 'Verweildauer')
ax[i-1].scatter(verweildauer_i_ugw, cs_bandwith_i_ugw-i-0.5, c="red", label = 'Unterer Grenzwert Verweildauer')
sns.kdeplot(verweildauer_i, ax=ax[i-1], shade=True, cumulative=False)
#Get data points of Kde PLot
data_x, data_y = ax[i-1].lines[0].get_data()
if data_y.max()>h:
h=data_y.max()
width=(10*nrows)/3
height=h
fig.set_size_inches(width,height)
plt.subplots_adjust(hspace=0)
print(height)
#Plot quartiles line
for k in range(len(quatrilesx)):
ax[i-1].axvline(quatrilesx[k], ymin=.3255, ymax=.3255+(height/width)*abs(data_y[find_nearest(data_x, quatrilesx[k])]), linestyle='dotted', color='black', linewidth=.6, alpha=.8)
ax[i-1].set_ylim(-0.5,1)
ax[i-1].set_ylabel('ZK ' + str(i))
ax[i-1].set_yticks([])
#draw the "y=0" line
ax[i-1].axhline(0, linestyle='--', color='blue', linewidth=.5, alpha=.35) # horizontal lines
handles, labels = ax[i-1].get_legend_handles_labels()
# create the legend again skipping this first entry
leg = ax[i-1].legend(handles[1:], labels[1:])
ax2=ax[i-1]
ax2 = ax[i-1].twinx()
ax2.grid(False)
ax2.set_ylabel("n = {}".format(s[i]), rotation=0, labelpad=25)
ax2.set_yticks([])
解决方案
推荐阅读
- javascript - 从 2 个数组创建一个字典( MAP )
- php - 在 jwt-auth 中是否可以为两个模型使用一个令牌?
- asp.net - 用户未登录时如何隐藏 CommandField?ASP.NET VB
- c++ - 如何为包含该类的非引用/指针的类定义朋友成员函数?
- django - 如何在 Django REST API 中使用自定义 APIView 保存模型实例?
- c++ - 7道题如何正确让电脑猜出用户的号码
- hibernate - CRUD 存储库不遵守 UNIQUE 约束
- laravel - Vue axios 向错误的 URL 发出 put 请求
- hibernate - Hibernate:如何在运行时动态注册 POJO 类?
- java - 仅 JavaFX TextField 可使用 css 更改焦点状态