heatmap (imshow)

Published by onesixx on

https://stackoverflow.com/questions/20525983/matplotlib-imshow-a-2d-array-with-plots-of-its-marginal-densities
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec

t = np.linspace(0, 31.3, 100)
f = np.linspace(0, 1000, 1000)
a = np.exp(-np.abs(f-200)/200)[:, None] * np.random.rand(t.size)
flim = (f.min(), f.max())
tlim = (t.min(), t.max())

gs = gridspec.GridSpec(2, 2, width_ratios=[1,3], height_ratios=[3,1])
ax = plt.subplot(gs[0,1])
axl = plt.subplot(gs[0,0], sharey=ax)
axb = plt.subplot(gs[1,1], sharex=ax)

ax.imshow(a, origin='lower', extent=tlim+flim, aspect='auto')
plt.xlim(tlim)

axl.plot(a.mean(1), f)
axb.plot(t, a.mean(0))
t <- seq(from=0, to=31.3, length.out=100)
f <- seq(from=0, to=1000, length.out=1000)
a <- exp(-abs(f-200)/200)  %*% t(runif(length(t)))  #runif(length(t))
#flim <- range(f)   # c(min(f), max(f))
#tlim <- range(t)

rownames(a) <- f
colnames(a) <- t
a_m <- melt(a)
ax <- a_m %>% ggplot(aes(x=Var2, y=Var1)) + geom_tile(aes(fill=value))
ax <- ax + theme_ipsum(base_size=9) + 
           theme(legend.position="none", axis.title.x=element_blank(), axis.title.y=element_blank(), plot.margin=unit(c(1,1,1,1),"lines"))
ax <- ax + scale_fill_viridis(discrete=F) 

xl <- cbind(rowMeans(a), f) %>% data.table()
axl <- xl %>% ggplot(aes(x=V1, y=f)) + geom_path(color="blue") 
axl <- axl + theme_ipsum(base_size=9) + 
             theme(axis.title.x=element_blank(), axis.title.y=element_blank(), plot.margin=unit(c(0,0,0,1),"lines"))

xb <- cbind(colMeans(a), t) %>% data.table()
axb <- xb %>% ggplot(aes(x=t, y=V1)) + geom_path(color="blue")
axb <- axb + theme_ipsum(base_size=9) + 
             theme(axis.title.x=element_blank(), axis.title.y=element_blank(), plot.margin=unit(c(0,0,1,0),"lines"))

empty <- NULL %>% ggplot() + geom_blank() + theme_void()

egg::ggarrange(axl,ax,empty, axb, widths=c(1,5), heights=c(3,1), ncol=2, nrow=2)
Categories: pjdlggplot2

onesixx

Blog Owner

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x