0

I've got a 2d kde plot with contours overlying a hexbin plot. I would like to set the contours and have them show as percentages. An example would be having the contours aligned with the 90% probability or 50% probability. Is there a simple method to do this?

Below is the code and figure obtained, also data is available should it help: 1

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats

xls = pd.ExcelFile('CSL-results.xlsx')
df = xls.parse("TAL"); TAL = df.dropna()

TALx = TAL.values\[:,0\]
TALy = TAL.values\[:,1\]

xmin = 0
xmax = 80
ymin = 0
ymax = 1

X, Y = np.mgrid\[xmin:xmax:100j, ymin:ymax:100j\]
positions = np.vstack(\[X.ravel(), Y.ravel()\])
TALvalues = np.vstack(\[TALx, TALy\])
TALkernel = stats.gaussian_kde(TALvalues)
fTAL = np.reshape(TALkernel(positions).T, X.shape)

fig = plt.figure(figsize = (10, 6), dpi = 200)
ax = fig.gca()
cfsetTAL = ax.contour(X, Y, fTAL, colors='#6c2d6c')
ax.clabel(cfsetTAL, inline=1, fontsize=6)
Hex_TAL = plt.hexbin(TALx,TALy, gridsize=50, mincnt=1, cmap='Blues')
plt.show()

enter image description here

Scott
  • 61
  • 7

1 Answers1

0

Okay I figured out how to do it by manually comparing it to the seaborn kdeplot levels to the contour levels. I'm not a fan of this method as it requires a bit of manual iteration so if anyone has a more automated (and better) method please feel free to comment.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
import seaborn as sns

xls = pd.ExcelFile('CSL-results.xlsx')
df = xls.parse("TAL"); TAL = df.dropna()

x = TAL.values\[:,0\]
y = TAL.values\[:,1\]

xmin = 0
xmax = 80
ymin = 0
ymax = 1

X, Y = np.mgrid\[xmin:xmax:100j, ymin:ymax:100j\]

positions = np.vstack(\[X.ravel(), Y.ravel()\])
values = np.vstack(\[x, y\])
kernel = stats.gaussian_kde(values)
f = np.reshape(kernel(positions).T, X.shape)

fig = plt.figure(figsize = (10, 6), dpi = 200)
ax = fig.gca()
fmt = {}

strs = \['50%', '70%', '80%', '90%'\]
sns.kdeplot(data=df,x="Confining Pressure", y="TAL", fill=False, levels=\[0.5, 0.7, 0.8, 0.9\], colors='r')
cfset = ax.contour(X, Y, f, colors='k', levels=\[0.078, 0.108, 0.130, 0.158\])
for l,s in zip( cfset.levels, strs ):
    fmt\[l\] = s

ax.clabel(cfset,cfset.levels\[::1\],inline=True,fmt=fmt, fontsize=6)
Hex_TAL = plt.hexbin(x,y, gridsize=50, mincnt=1, cmap='Blues')

plt.show()

enter image description here

Scott
  • 61
  • 7