- 以热年代学数据为例
- 完整代码:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import gaussian_kde
plt.rcParams['font.family'] = 'Arial Unicode MS'
plt.rcParams['font.size'] = 10
plt.rcParams["pdf.fonttype"] = 42
upperage =40
bins=30
bw_method = 0.1
alpha = 1
color = ['#d1d4bc','#feaef8','#76fe76','#9cbdf2','gray']
ylower = -60
yupper = 90
file = 'data.xls'
data = pd.read_excel(file)
data = data[data['age']<=upperage]
data_ahe = data[data['Methods']=='AHe']
data_aft = data[data['Methods']=='AFT']
data_zhe = data[data['Methods']=='ZHe']
data_zft = data[data['Methods']=='ZFT']
fig,ax = plt.subplots()
ahe = np.histogram(data_ahe['age'],bins=bins,range=[0,upperage])
aft = np.histogram(data_aft['age'],bins=bins,range=[0,upperage])
ax.bar(aft[1][:-1],aft[0],width=np.diff(aft[1]),alpha=alpha,edgecolor=color[4],color=color[1],label='AFT')
ax.bar(ahe[1][:-1],ahe[0],width=np.diff(ahe[1]),alpha=alpha,edgecolor=color[4],color=color[0],label='AHe')
zhe = np.histogram(data_zhe['age'],bins=bins,range=[0,upperage])
zft = np.histogram(data_zft['age'],bins=bins,range=[0,upperage])
ax.bar(zhe[1][:-1],-zhe[0],width=np.diff(zhe[1]),alpha=alpha,edgecolor=color[4],color=color[2],label='ZHe')
ax.bar(zft[1][:-1],-zft[0],width=np.diff(zft[1]),alpha=alpha,edgecolor=color[4],color=color[3],label='ZFT')
ax.set_ylim(ylower,yupper)
ax.yaxis.set_visible(False)
ax.spines['top'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.legend()
ax1=ax.twinx()
data_x = np.linspace(0,upperage,1000)
data_ahe_kde = gaussian_kde(data_ahe['age'],bw_method=bw_method)
data_ahe_y=data_ahe_kde(data_x)
data_aft_kde = gaussian_kde(data_aft['age'],bw_method=bw_method)
data_aft_y=data_aft_kde(data_x)
data_zhe_kde = gaussian_kde(data_zhe['age'],bw_method=bw_method)
data_zhe_y=data_zhe_kde(data_x)
data_zft_kde = gaussian_kde(data_zft['age'],bw_method=bw_method)
data_zft_y=data_zft_kde(data_x)
ax1.plot(data_x, data_ahe_y, label='KDE',color=color[0])
ax1.plot(data_x, data_aft_y, label='KDE',color=color[1])
ax1.plot(data_x, -data_zhe_y, label='KDE',color=color[2])
ax1.plot(data_x, -data_zft_y, label='KDE',color=color[3])
ax1.set_ylim(ylower/1000,yupper/1000)
ax1.spines['top'].set_visible(False)
ax1.spines['left'].set_visible(False)
ax.set_xlabel('Age (Ma)')
ax1.set_ylabel('Density')
ax1.axhline(0)
ticks=ax1.get_yticks()
ax1.set_yticklabels([round(abs(x),2) for x in ticks])
plt.xlim(upperage,0)
plt.tight_layout()
plt.savefig('res.pdf')
plt.show()