Code
# install.packages(c("plotly","ggseg.formats","ggseg.meshes","freesurferformats","misc3d",
# "geometry"))
library(plotly)Plotly’s MRI Reconstruction app shows a human brain that turns under the mouse (its code). This data story draws such a brain with plotly in R and adds its anatomy: the names of its parts, what each part does, how large it is, and how the parts are wired together. Six questions:
The brain is fsaverage, the average brain of FreeSurfer, a widely used program that measures the cortex on MRI scans: the brains of many adults, laid over each other fold to fold (Fischl et al. 1999). Its parts come from three sources: the Desikan–Killiany atlas of the cortex, with 34 regions in each hemisphere, bounded mostly by the folds (Desikan et al. 2006); FreeSurfer’s segmentation of the same brain, a volume of cubes of 1 mm each labeled with the structure it lies in (Fischl et al. 2002), from which the page draws the structures under the cortex and the ventricles; and TRACULA, an atlas of 42 bundles of white matter traced from diffusion MRI (Yendiki et al. 2011; Maffei et al. 2021). The cortex, its atlas and TRACULA come with the R packages ggseg.meshes and ggseg.formats (Mowinckel and Vidal-Piñeiro 2020); the segmentation, 365 KB, is downloaded once from the server of the fsbrain package (Schäfer and Ecker 2020).
The words of this page:
# short labels of numbers, lists and shifts for the text
number<-function(x) {
result<-format(round(x),big.mark=",",trim=TRUE)
return(result)
}
one<-function(x) {
result<-format(round(x,1),nsmall=1,trim=TRUE)
return(result)
}
percent<-function(x) {
result<-paste0(round(x),"%")
return(result)
}
and_list<-function(x) {
result<-if(length(x)<2) paste(x) else paste(paste(x[-length(x)],collapse=", "),"and",
x[length(x)])
return(result)
}
count_words<-function(n) {
words<-c("one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve")
result<-if(n<=12) words[n] else number(n)
return(result)
}
upper_first<-function(x) {
result<-paste0(toupper(substr(x,1,1)),substring(x,2))
return(result)
}
lower_first<-function(x) {
result<-paste0(tolower(substr(x,1,1)),substring(x,2))
return(result)
}
# "24.0 mm further forward" or "3.5 mm further back"
shift_words<-function(x,positive,negative) {
result<-paste(one(abs(x)),"mm",if(x>=0) positive else negative)
return(result)
}# a surface of the cortex of one hemisphere of fsaverage5, 10,242 points joined in 20,480 triangles.
# ggseg.meshes keeps it turned a quarter round, with x from the back to the front: here x runs from
# left to right, y from the back to the front and z from the bottom to the top, in mm
read_surface<-function(hemisphere,surface) {
mesh<-ggseg.meshes::get_cortical_mesh(hemisphere,surface)
vertices<-cbind(x=-mesh$vertices$y,y=mesh$vertices$x,z=mesh$vertices$z)
result<-list(vertices=vertices,faces=as.matrix(mesh$faces))
return(result)
}
# the area of each triangle of a surface, in mm²
triangle_area<-function(vertices,faces) {
a<-vertices[faces[,2],]-vertices[faces[,1],]
b<-vertices[faces[,3],]-vertices[faces[,1],]
result<-sqrt((a[,2]*b[,3]-a[,3]*b[,2])^2+(a[,3]*b[,1]-a[,1]*b[,3])^2+
(a[,1]*b[,2]-a[,2]*b[,1])^2)/2
return(result)
}
# the Desikan-Killiany atlas: the points of each region (numbered from 0), and the lobe of each
atlas<-ggseg.formats::dk()
atlas_points<-atlas$data$vertices
atlas_lobes<-unique(as.data.frame(atlas$core)[,c("label","lobe")])
hemispheres<-c(lh="left",rh="right")
faces<-list()
points<-data.frame()
pial_area<-0
for(h in names(hemispheres)) {
pial<-read_surface(h,"pial")
white<-read_surface(h,"white")$vertices
middle<-read_surface(h,"midthickness")$vertices
# the inflated surface comes from ggseg.formats, already in this frame but with each hemisphere
# around x = 0: they move apart, their inner sides 4 mm from the middle
inflated<-as.matrix(ggseg.formats::get_brain_mesh(h,"inflated")$vertices)
inflated[,1]<-if(h=="lh") inflated[,1]-max(inflated[,1])-4 else inflated[,1]-min(inflated[,1])+4
faces[[h]]<-pial$faces
# the region of each point; the points of no region are the medial wall, where the hemisphere is
# cut away from the structures under it (the atlas calls a part of it "corpus callosum")
region<-rep("medialwall",nrow(pial$vertices))
for(k in grep(paste0("^",h,"_"),atlas_points$label))
region[atlas_points$vertices[[k]]+1]<-sub("^[lr]h_","",atlas_points$label[k])
# the area of the cortex around each point, measured halfway through its thickness: a third of
# each triangle that the point is a corner of
triangles<-triangle_area(middle,pial$faces)
area<-as.vector(rowsum(rep(triangles/3,3),as.vector(pial$faces)))
pial_area<-pial_area+sum(triangle_area(pial$vertices,pial$faces))
# the thickness at a point: the distance from the outer (pial) surface of the cortex to the inner
# (white) one, which have the same points
points<-rbind(points,data.frame(hemisphere=hemispheres[[h]],region=region,pial$vertices,
inflated_x=inflated[,1],inflated_y=inflated[,2],
inflated_z=inflated[,3],middle_x=middle[,1],
middle_y=middle[,2],middle_z=middle[,3],area=area,
thickness=sqrt(rowSums((pial$vertices-white)^2))))
}
points$lobe<-atlas_lobes$lobe[match(paste0(substr(points$hemisphere,1,1),"h_",points$region),
atlas_lobes$label)]
xyz<-as.matrix(points[,c("x","y","z")])# the wrap of each hemisphere: the convex hull of its points. Each row of hull$normals is the plane
# of one of the hull's triangles, a x + b y + c z + d = 0, with (a, b, c) pointing outwards. The
# depth of a point under the wrap is its distance to the nearest of those planes, worked out for
# 2,000 points at a time to keep the table of distances small
points$depth<-NA
wrap_area<-0
for(h in hemispheres) {
rows<-which(points$hemisphere==h)
hull<-geometry::convhulln(xyz[rows,],output.options="n FA")
wrap_area<-wrap_area+hull$area
for(block in split(rows,ceiling(seq_along(rows)/2000))) {
distance<-xyz[block,]%*%t(hull$normals[,1:3])+
matrix(hull$normals[,4],length(block),nrow(hull$normals),byrow=TRUE)
points$depth[block]<-apply(-distance,1,min)
}
}# the names of the regions and of the lobes and what they do, simplified from textbooks (see the
# sources); "medialwall" is not a region of the cortex
regions<-read.csv(sep="|",text="code|name|role
bankssts|Superior temporal sulcus|Its banks: making sense of speech, faces and movements
caudalanteriorcingulate|Caudal anterior cingulate|Noticing mistakes and conflicts, and pain
caudalmiddlefrontal|Caudal middle frontal gyrus|Moving the eyes (frontal eye field), attention
cuneus|Cuneus|Seeing: visual areas for the lower half of the view
entorhinal|Entorhinal cortex|The gateway to the hippocampus: memory and finding the way
fusiform|Fusiform gyrus|Recognising faces, bodies and written words
inferiorparietal|Inferior parietal lobule|Reading, numbers and meaning (the angular gyrus)
inferiortemporal|Inferior temporal gyrus|Recognising objects by sight
isthmuscingulate|Isthmus of the cingulate|Memory and finding the way (the retrosplenial cortex)
lateraloccipital|Lateral occipital cortex|Seeing shapes, objects and motion
lateralorbitofrontal|Lateral orbitofrontal cortex|Learning from rewards and losses
lingual|Lingual gyrus|Seeing: visual areas for the upper half of the view
medialorbitofrontal|Medial orbitofrontal cortex|The value of things, and choosing between them
middletemporal|Middle temporal gyrus|The meanings of words and things
parahippocampal|Parahippocampal gyrus|Recognising places and scenes, and memory
paracentral|Paracentral lobule|Moving and feeling the legs and feet
parsopercularis|Pars opercularis|Speaking: part of Broca's area, mostly on the left
parsorbitalis|Pars orbitalis|The meanings of words and sentences
parstriangularis|Pars triangularis|Language: part of Broca's area, mostly on the left
pericalcarine|Pericalcarine cortex|Seeing: the primary visual cortex, first to get the eyes' signals
postcentral|Postcentral gyrus|Touch and the sense of the body: the primary somatosensory cortex
posteriorcingulate|Posterior cingulate|Remembering, thinking about oneself and daydreaming
precentral|Precentral gyrus|Moving the body: the primary motor cortex
precuneus|Precuneus|Imagining scenes, remembering, and the self in space
rostralanteriorcingulate|Rostral anterior cingulate|Emotions, and keeping them in check
rostralmiddlefrontal|Rostral middle frontal gyrus|Planning, holding things in mind, self-control
superiorfrontal|Superior frontal gyrus|Planning movements (supplementary motor area), thinking
superiorparietal|Superior parietal lobule|Where things are, and reaching for them
superiortemporal|Superior temporal gyrus|Hearing and understanding speech (Wernicke's area)
supramarginal|Supramarginal gyrus|The sounds of words, and using tools and gestures
frontalpole|Frontal pole|The most abstract planning: keeping other options in mind
temporalpole|Temporal pole|Knowing people and things, and emotion
transversetemporal|Transverse temporal gyrus|Hearing: the primary auditory cortex (Heschl's gyrus)
insula|Insula|Feeling the inside of the body, taste, and disgust
medialwall|Medial wall|Not cortex: where the hemisphere is cut away from the structures under it")
lobes<-read.csv(sep="|",text="code|name|role
frontal|Frontal lobe|Planning, deciding, speaking and moving
parietal|Parietal lobe|Touch, and where things are
temporal|Temporal lobe|Hearing, language, memory and recognising things
occipital|Occipital lobe|Seeing
cingulate|Cingulate gyrus|Emotion, attention and memory
insula|Insula|Feelings from inside the body, and taste")
# a region's (or a lobe's) area in cm², and its thickness and its depth under the wrap in mm,
# weighted by the area around each point; deep: the share of its area more than 5 mm under the wrap
summarise_cortex<-function(x,group) {
totals<-rowsum(cbind(area=x$area,thickness=x$thickness*x$area,depth=x$depth*x$area,
deep=(x$depth>5)*x$area),group)
result<-data.frame(key=rownames(totals),area=totals[,"area"]/100,
thickness=totals[,"thickness"]/totals[,"area"],
depth=totals[,"depth"]/totals[,"area"],
deep=100*totals[,"deep"]/totals[,"area"])
return(result)
}
cortex<-points[!points$region%in%c("medialwall","corpuscallosum"),]
region_both<-summarise_cortex(cortex,cortex$region)
region_both$lobe<-cortex$lobe[match(region_both$key,cortex$region)]
region_both$name<-regions$name[match(region_both$key,regions$code)]
region_side<-summarise_cortex(cortex,paste(cortex$hemisphere,cortex$region))
lobe_both<-summarise_cortex(cortex,cortex$lobe)
lobe_both$name<-lobes$name[match(lobe_both$key,lobes$code)]
lobe_both$share<-100*lobe_both$area/sum(lobe_both$area)# FreeSurfer's segmentation of fsaverage (aseg.mgz): a volume of 256 × 256 × 256 cubes of 1 mm, each
# labeled with the structure it lies in. The server of the fsbrain package keeps a copy (365 KB);
# the page keeps its download, and the checksum makes sure that it is the file the page was written
# for
download_file<-function(url,file,tries=3) {
for(k in seq_len(tries)) {
done<-tryCatch(download.file(url,file,mode="wb",quiet=TRUE)==0,error=function(e) FALSE)
if(done)
return(invisible(file))
Sys.sleep(10)
}
stop("Could not download ",url)
}
cache<-tools::R_user_dir("illustration","cache")
dir.create(cache,recursive=TRUE,showWarnings=FALSE)
aseg_file<-file.path(cache,"fsaverage_aseg.mgz")
aseg_url<-"https://rcmd.org/projects/nitestdata/subjects_dir/fsaverage/mri/aseg.mgz"
if(!file.exists(aseg_file))
download_file(aseg_url,aseg_file)
stopifnot(unname(tools::md5sum(aseg_file))=="b4a8f385370e5c831cdbe2f2a00d2d51")
aseg<-freesurferformats::read.fs.mgh(aseg_file,with_header=TRUE)
labels<-aseg$data[,,,1]
# the cubes of each label (0 to 255), counted: 1,000 cubes of 1 mm make a cm³
cubes<-tabulate(as.vector(labels)+1,nbins=256)
# from a cube (its column, row and slice, numbered from 1) to mm in the frame of the cortex, and
# the label of the cube at a point
voxel_matrix<-freesurferformats::mghheader.vox2ras.tkreg(aseg$header)
voxel_xyz<-function(ijk) {
result<-(cbind(ijk-1,1)%*%t(voxel_matrix))[,1:3,drop=FALSE]
return(result)
}
label_at<-function(xyz) {
ijk<-round((cbind(xyz,1)%*%t(solve(voxel_matrix)))[,1:3,drop=FALSE])+1
inside<-rowSums(ijk>=1&ijk<=256)==3
result<-rep(NA,nrow(xyz))
result[inside]<-labels[ijk[inside,,drop=FALSE]]
return(result)
}
# the volume and the surfaces should lie in the same frame: the points halfway through the cortex
# should fall in cubes labeled cortex (3 on the left, 42 on the right). The share of them that do,
# with the volume where it is and moved by up to 2 mm in each direction
on_cortex<-function(shift,middle,expected) {
result<-100*mean(label_at(sweep(middle,2,shift,"+"))==expected,na.rm=TRUE)
return(result)
}
middle<-as.matrix(points[,c("middle_x","middle_y","middle_z")])
moves<-expand.grid(dx=-2:2,dy=-2:2,dz=-2:2)
moves$share<-apply(moves,1,on_cortex,middle=middle,
expected=ifelse(points$hemisphere=="left",3,42))
in_place<-moves$share[moves$dx==0&moves$dy==0&moves$dz==0]The volume lies in the frame of the cortex: 74% of the points halfway through the cortex fall in cubes labeled cortex (most of the others lie on the medial wall or at the edge of the cortex), and no move of up to 2 mm in any direction does better.
# the structures under the cortex and the ventricles: their names, the labels of their cubes on the
# left, on the right or in the middle, and what they do
deep_list<-read.csv(sep="|",colClasses="character",text="code|name|left|right|middle|role
cerebellum|Cerebellum|7 8|46 47||Balance, coordination and the timing of movements
brainstem|Brain stem|||16|Breathing, heartbeat, sleep and waking; joins the brain to the spinal cord
thalamus|Thalamus|10|49||The relay station of the senses (all but smell) on the way to the cortex
caudate|Caudate nucleus|11|50||Basal ganglia: learning, goals and habits
putamen|Putamen|12|51||Basal ganglia: movement and habits
pallidum|Globus pallidus|13|52||Basal ganglia: lets movements go ahead or holds them back
hippocampus|Hippocampus|17|53||Making new memories, and finding the way
amygdala|Amygdala|18|54||Emotion, fear, and noticing danger
accumbens|Nucleus accumbens|26|58||Reward and motivation
ventraldc|Ventral diencephalon|28|60||The hypothalamus and nuclei around it: hunger, sleep, hormones
callosum|Corpus callosum|||251 252 253 254 255|The bridge of nerve fibres between the hemispheres
chiasm|Optic chiasm|||85|Where the optic nerves cross: each hemisphere sees the opposite half")
ventricle_list<-read.csv(sep="|",colClasses="character",text="code|name|left|right|middle|role
lateral|Lateral ventricles|4 5|43 44||One in each hemisphere, arching back into the temporal lobe
third|Third ventricle|||14|A narrow slit between the two halves of the thalamus
fourth|Fourth ventricle|||15|Between the brain stem and the cerebellum; the fluid flows out from it
choroid|Choroid plexus|31|63||Small blood vessels in the ventricles that make most of the fluid")
# the volume of a list of labels, in cm³, and of each structure on each side
label_volume<-function(numbers) {
result<-if(numbers=="") 0 else sum(cubes[as.integer(strsplit(numbers," ")[[1]])+1])/1000
return(result)
}
for(side in c("left","right","middle")) {
deep_list[[paste0(side,"_volume")]]<-sapply(deep_list[[side]],label_volume,USE.NAMES=FALSE)
ventricle_list[[paste0(side,"_volume")]]<-sapply(ventricle_list[[side]],label_volume,
USE.NAMES=FALSE)
}
deep_list$volume<-deep_list$left_volume+deep_list$right_volume+deep_list$middle_volume
ventricle_list$volume<-ventricle_list$left_volume+ventricle_list$right_volume+
ventricle_list$middle_volume
# the brain: every labeled cube but those of the spaces filled with fluid (the ventricles and the
# fluid around the brain stem)
fluid<-c(4,5,14,15,24,43,44,72)
brain_volume<-(sum(cubes[-1])-sum(cubes[fluid+1]))/1000tracts<-ggseg.formats::tracula()$data$centerlines
# the tracts come in a frame of their own, and mirrored: those of the left hemisphere ("lh.") lie
# at positive x. Mirrored back, they are laid on the volume where most of their points fall in
# white matter (2, 41, 7, 46, 77) or in the deep structures that they cross (the brain stem 16, the
# ventral diencephalon 28 and 60, the corpus callosum 251 to 255, the thalamus 10 and 49, the optic
# chiasm 85): first every 1 mm up to 30 mm forwards or backwards and up or down, then every 0.5 mm
# around the best, from side to side too
tract_points<-lapply(tracts$points,function(m) cbind(-m[,1],m[,2],m[,3]))
all_points<-do.call(rbind,tract_points)
white<-c(2,41,7,46,77,16,28,60,251:255,10,49,85)
in_white<-function(shift,xyz) {
result<-100*mean(label_at(sweep(xyz,2,shift,"+"))%in%white)
return(result)
}
first_moves<-expand.grid(dx=0,dy=-30:30,dz=-30:30)
first_moves$share<-apply(first_moves,1,in_white,xyz=all_points)
start<-first_moves[which.max(first_moves$share),]
moves_near<-expand.grid(dx=seq(-2,2,by=0.5),dy=start$dy+seq(-1.5,1.5,by=0.5),
dz=start$dz+seq(-1.5,1.5,by=0.5))
moves_near$share<-apply(moves_near,1,in_white,xyz=all_points)
tract_fit<-moves_near[which.max(moves_near$share),]
unmoved<-in_white(c(0,0,0),all_points)
tract_shift<-c(tract_fit$dx,tract_fit$dy,tract_fit$dz)
tract_points<-lapply(tract_points,function(m) sweep(m,2,tract_shift,"+"))
# each tract: its side, its code without the side ("af", "cc.genu") and its length in mm
code<-sub("\\.bbr\\.prep$","",tracts$label)
tract_list<-data.frame(side=ifelse(grepl("^lh\\.",code),"left",
ifelse(grepl("^rh\\.",code),"right","middle")),
code=sub("^[lr]h\\.","",code))
tract_list$length<-sapply(tract_points,function(m) sum(sqrt(rowSums(diff(m)^2))))Mirrored and moved 14.5 mm backwards, 10.0 mm upwards and 0.5 mm to the right, 89% of the points of the tracts fall in white matter or in the deep structures that they cross, the most for any move tried; where they come, 50% do.
# the tracts: their names, their group and what they do
tract_names<-read.csv(sep="|",text="code|name|group|role
cc.rostrum|Corpus callosum: rostrum|commissural|Links the orbitofrontal cortex of the two sides
cc.genu|Corpus callosum: genu|commissural|Links the prefrontal cortex of the two hemispheres
cc.bodypf|Corpus callosum: body, prefrontal|commissural|Links the prefrontal cortex of the two sides
cc.bodypm|Corpus callosum: body, premotor|commissural|Links the premotor cortex of the two sides
cc.bodyc|Corpus callosum: body, central|commissural|Links the motor and touch strips of both sides
cc.bodyp|Corpus callosum: body, parietal|commissural|Links the parietal lobes
cc.bodyt|Corpus callosum: body, temporal|commissural|Links the temporal lobes
cc.splenium|Corpus callosum: splenium|commissural|Links the occipital lobes
acomm|Anterior commissure|commissural|Links the two temporal lobes, and smell
af|Arcuate fasciculus|association|Language: links the speech areas at the front and at the back
slf1|Superior longitudinal fasciculus I|association|Movement and attention, along the top
slf2|Superior longitudinal fasciculus II|association|Attention to where things are
slf3|Superior longitudinal fasciculus III|association|Language and gestures, along the side
ilf|Inferior longitudinal fasciculus|association|Recognising what is seen: occipital to temporal
mlf|Middle longitudinal fasciculus|association|Hearing and language: temporal to parietal
emc|Extreme capsule|association|Language: links the temporal lobe with the frontal lobe
fat|Frontal aslant tract|association|Starting to speak and act: links the top of the frontal lobe
uf|Uncinate fasciculus|limbic|Emotion and memory: temporal pole to orbitofrontal cortex
cbd|Cingulum, upper part|limbic|Attention and emotion: runs inside the cingulate gyrus
cbv|Cingulum, lower part|limbic|Memory: links the cingulate gyrus with the hippocampal region
fx|Fornix|limbic|Memory: carries signals out of the hippocampus
cst|Corticospinal tract|projection|Moving: from the motor cortex down to the spinal cord
atr|Anterior thalamic radiation|projection|Links the thalamus with the front of the brain
or|Optic radiation|projection|Seeing: from the thalamus to the visual cortex
ar|Acoustic radiation|projection|Hearing: from the thalamus to the auditory cortex
mcp|Middle cerebellar peduncle|cerebellar|Carries signals from the cortex, through the pons")
groups<-c(commissural="Commissural: across the hemispheres",
association="Association: within a hemisphere",
projection="Projection: cortex to thalamus and spinal cord",
limbic="Limbic: memory and emotion",cerebellar="Cerebellar: to the cerebellum")
tract_list<-cbind(tract_list,tract_names[match(tract_list$code,tract_names$code),-1])# a simpler copy of a surface: its points are gathered into cubes of `size` mm and the points of a
# cube become one, their mean; triangles that shrink to a line or a point go
simplify_mesh<-function(vertices,faces,size) {
cube<-paste(round(vertices[,1]/size),round(vertices[,2]/size),round(vertices[,3]/size))
group<-match(cube,unique(cube))
centres<-rowsum(vertices,group)/as.vector(table(group))
triangles<-matrix(group[faces],ncol=3)
triangles<-triangles[triangles[,1]!=triangles[,2]&triangles[,2]!=triangles[,3]&
triangles[,1]!=triangles[,3],,drop=FALSE]
triangles<-triangles[!duplicated(t(apply(triangles,1,sort))),,drop=FALSE]
result<-list(vertices=centres,faces=triangles-1)
return(result)
}
# the surface of a structure from the cubes of its labels. The cubes are blurred a little (by a bell
# curve of 0.8 mm, one direction at a time), so that the surface is smooth rather than made of
# steps; misc3d's marching cubes trace it where the blurred value is one half; and it is simplified
# into cubes of 2 mm, or 3 mm for the largest structures (over 20 cm³)
smooth_line<-function(v,k) {
n<-length(v)
h<-(length(k)-1)/2
result<-as.vector(stats::filter(c(rep(0,h),v,rep(0,h)),k,sides=2))[(h+1):(h+n)]
return(result)
}
blur<-function(a,sigma) {
k<-dnorm(-3:3,sd=sigma)
k<-k/sum(k)
a<-apply(a,c(2,3),smooth_line,k=k)
a<-aperm(apply(a,c(1,3),smooth_line,k=k),c(2,1,3))
result<-aperm(apply(a,c(1,2),smooth_line,k=k),c(2,3,1))
return(result)
}
structure_labels<-function(x) {
result<-as.integer(unlist(strsplit(c(x$left,x$right,x$middle)," ")))
return(result)
}
label_surface<-function(numbers) {
inside<-array(labels%in%numbers,dim(labels))
found<-which(inside,arr.ind=TRUE)
low<-pmax(apply(found,2,min)-4,1)
high<-pmin(apply(found,2,max)+4,256)
box<-inside[low[1]:high[1],low[2]:high[2],low[3]:high[3]]+0
soup<-misc3d::computeContour3d(blur(box,0.8),maxvol=1,level=0.5,x=low[1]:high[1],
y=low[2]:high[2],z=low[3]:high[3])
# the corners of the triangles, each written once
key<-paste(round(soup[,1],4),round(soup[,2],4),round(soup[,3],4))
corners<-voxel_xyz(soup[!duplicated(key),,drop=FALSE])
triangles<-matrix(match(key,unique(key)),ncol=3,byrow=TRUE)
result<-simplify_mesh(corners,triangles,if(nrow(found)>20000) 3 else 2)
return(result)
}
deep_shapes<-list()
for(k in seq_len(nrow(deep_list)))
deep_shapes[[deep_list$code[k]]]<-label_surface(structure_labels(deep_list[k,]))
ventricle_shapes<-list()
for(k in seq_len(nrow(ventricle_list)))
ventricle_shapes[[ventricle_list$code[k]]]<-label_surface(structure_labels(ventricle_list[k,]))
# a coarse copy of the cortex, drawn as glass around the structures and the tracts. fsaverage5 was
# made by dividing each triangle of an icosahedron into four, five times over, and its first 2,562
# points are those of the fourth time: their triangles are the convex hull of those points on the
# sphere, each turned to face outwards as the lighting needs
coarse<-list()
for(h in names(hemispheres)) {
sphere<-read_surface(h,"sphere")$vertices[1:2562,]
sphere<-sweep(sphere,2,colMeans(sphere))
triangles<-geometry::convhulln(sphere)
a<-sphere[triangles[,2],]-sphere[triangles[,1],]
b<-sphere[triangles[,3],]-sphere[triangles[,1],]
normal<-cbind(a[,2]*b[,3]-a[,3]*b[,2],a[,3]*b[,1]-a[,1]*b[,3],a[,1]*b[,2]-a[,2]*b[,1])
inwards<-rowSums(normal*sphere[triangles[,1],])<0
triangles[inwards,]<-triangles[inwards,c(1,3,2)]
coarse[[h]]<-list(vertices=xyz[points$hemisphere==hemispheres[[h]],][1:2562,],
faces=triangles-1)
}
# the cortex in pieces, one for each region of each hemisphere, so that the pointer can name the
# region: the rows of its points in `points`, and its triangles numbered from 0 within the piece. A
# triangle belongs to the region of its first corner
points$region[points$region=="corpuscallosum"]<-"medialwall"
pieces<-list()
for(h in names(hemispheres)) {
rows<-which(points$hemisphere==hemispheres[[h]])
corner<-points$region[rows][faces[[h]][,1]]
for(r in unique(corner)) {
triangles<-faces[[h]][corner==r,,drop=FALSE]
used<-sort(unique(as.vector(triangles)))
pieces[[length(pieces)+1]]<-list(hemisphere=hemispheres[[h]],region=r,rows=rows[used],
faces=matrix(match(triangles,used)-1,ncol=3))
}
}dark_gray<-"#6b6b6b" # also the color of the notes and the labels
light_gray<-"#d9d9d9" # the medial wall and the corpus callosum
glass_gray<-"#a8a8a8"
# the lobes, the structures under the cortex, the groups of tracts and the ventricles, told apart
# also by color-blind readers (every pair checked)
lobe_colours<-c(frontal="#56B4E9",parietal="#E69F00",temporal="#009E73",occipital="#CC79A7",
cingulate="#D55E00",insula="#F0E442")
deep_colours<-c(cerebellum="#E69F00",brainstem="#4a4a4a",thalamus="#0072B2",caudate="#56B4E9",
putamen="#CC79A7",pallidum="#542788",hippocampus="#F0E442",amygdala="#D55E00",
accumbens="#009E73",ventraldc="#8c564b",callosum=light_gray,chiasm="#1a1a1a")
group_colours<-c(commissural="#0072B2",association="#E69F00",projection="#009E73",
limbic="#CC79A7",cerebellar="#D55E00")
ventricle_colours<-c(lateral="#0072B2",third="#56B4E9",fourth="#009E73",choroid="#D55E00")
# the color scales of the depth under the wrap (pale on the surface, dark deep down) and of the
# thickness, and the four bands of depth of question 2
depth_scale<-list(list(0,"#deebf7"),list(0.25,"#9ecae1"),list(0.5,"#4292c6"),list(0.75,"#2171b5"),
list(1,"#08306b"))
thickness_scale<-list(list(0,"#fde725"),list(0.25,"#5ec962"),list(0.5,"#21918c"),
list(0.75,"#3b528b"),list(1,"#440154"))
band_colours<-c("#c6dbef","#6baed6","#2171b5","#08306b")
# the source of a chart, as a note under it, and the common layout; note_shift moves the note down
# by a number of pixels, which stays the same however tall the plot is
chart<-function(p,title,source,annotations=list(),margin=list(t=70,b=90),note_y=-0.16,
note_shift=0,...) {
note<-list(text=paste("Source:",source),xref="paper",yref="paper",x=0,y=note_y,xanchor="left",
yanchor="top",yshift=note_shift,align="left",showarrow=FALSE,
font=list(size=11,color=dark_gray))
result<-layout(p,
title=list(text=title,x=0.02,xanchor="left",y=0.97,yanchor="top"),
margin=margin,
annotations=c(annotations,list(note)),
...) %>%
config(displaylogo=FALSE)
return(result)
}
legend_top<-list(orientation="h",x=0,y=1.02,yanchor="bottom")
fsaverage<-"FreeSurfer's fsaverage5 and the Desikan-Killiany atlas (ggseg.meshes, ggseg.formats)."
# 3D charts. A mesh of triangles, numbered from 0, in tenths of a mm as whole numbers: plotly for R
# writes any other number with 17 digits, -38.700000000000003 for -38.7. The axes are hidden, and
# the tracts are drawn in tenths of a mm too
add_mesh<-function(p,vertices,faces,name,...) {
result<-add_trace(p,type="mesh3d",x=round(10*vertices[,1]),y=round(10*vertices[,2]),
z=round(10*vertices[,3]),i=faces[,1],j=faces[,2],k=faces[,3],name=name,...)
return(result)
}
# the last step of a 3D chart: build it, drop its second copy of every number ("attrs"), and give
# each trace its color and its text for the pointer, which plotly for R would leave out (the
# color of a mesh, in whose place it puts a color scale) or repeat for every point (the text); NA
# leaves a trace as it is
finish_3d<-function(p,colours,meta) {
result<-plotly_build(p)
result$x$attrs<-NULL
for(k in seq_along(result$x$data)) {
if(!is.na(colours[k])) {
result$x$data[[k]]$color<-colours[[k]]
result$x$data[[k]]$colorscale<-NULL
}
if(!is.na(meta[k])) {
result$x$data[[k]]$meta<-meta[[k]]
result$x$data[[k]]$hovertemplate<-"%{meta}<extra></extra>"
}
}
return(result)
}
# the light, from above, and the scene: no axes, the brain in its true shape, turned by dragging
lighting<-list(ambient=0.45,diffuse=0.75,specular=0.15,roughness=0.6,fresnel=0.1)
glass_lighting<-list(ambient=0.9,diffuse=0.2,specular=0,roughness=1,fresnel=0.2)
above<-list(x=0,y=0,z=1e5)
scene<-function(eye=list(x=-1.35,y=0.25,z=0.3),domain=list(x=c(0,1),y=c(0,1))) {
axis<-list(visible=FALSE)
result<-list(xaxis=axis,yaxis=axis,zaxis=axis,aspectmode="data",dragmode="turntable",
camera=list(eye=eye),domain=domain)
return(result)
}
# buttons under a 3D chart that turn the brain to one of six views
views<-list(Left=c(-1.5,0,0.1),Right=c(1.5,0,0.1),Front=c(0,1.5,0.1),Back=c(0,-1.5,0.1),
Top=c(0,0,1.6),Below=c(0,0,-1.6))
view_buttons<-list()
for(v in names(views)) {
up<-if(v%in%c("Top","Below")) list(x=0,y=1,z=0) else list(x=0,y=0,z=1)
eye<-list(x=views[[v]][1],y=views[[v]][2],z=views[[v]][3])
camera<-list(eye=eye,up=up,center=list(x=0,y=0,z=0))
view_buttons[[v]]<-list(label=v,method="relayout",args=list(list(scene.camera=camera)))
}
view_menu<-list(type="buttons",direction="right",x=0,y=0,xanchor="left",yanchor="top",
showactive=FALSE,buttons=unname(view_buttons))
# a volume in cm³, to a tenth, or to a hundredth below 0.1 cm³ (the optic chiasm)
volume_text<-function(x) {
result<-if(x<0.1) format(round(x,2),nsmall=2) else one(x)
return(result)
}
# the volume of a structure: on each side, or in all for one in the middle
volume_words<-function(x) {
result<-if(x$left_volume>0) paste0(volume_text(x$left_volume)," cm³ on the left, ",
volume_text(x$right_volume)," on the right") else
paste0(volume_text(x$volume)," cm³")
return(result)
}
# the text for the pointer: a name in bold, and lines under it
pointer_text<-function(name,...) {
result<-paste0("<b>",name,"</b><br>",paste(...,sep="<br>"))
return(result)
}Six lobes and 34 regions in each hemisphere. Spread out flat, the cortex of the average brain would cover 1,286 cm², a square of 36 cm on each side (measured halfway through its thickness); the left hemisphere has 0.1% less of it than the right. The frontal lobe has 36% of it, the parietal lobe 25%, the temporal lobe 21% and the occipital lobe 11%; the cingulate gyrus, on the inner side of each hemisphere, and the insula, hidden under the frontal and temporal lobes, share the rest. Of the regions, the superior frontal gyrus is the largest, 115 cm² in the two hemispheres together, and the frontal pole the smallest, 5 cm².
p<-plot_ly()
lobe_trace<-c()
region_trace<-c()
meta<-c()
for(piece in pieces) {
region<-regions[regions$code==piece$region,]
lobe<-region_both$lobe[region_both$key==piece$region]
name<-paste0(region$name,", ",piece$hemisphere)
p<-add_mesh(p,xyz[piece$rows,],piece$faces,name,flatshading=FALSE,lighting=lighting,
lightposition=above,showlegend=FALSE)
if(piece$region=="medialwall") {
lobe_trace<-c(lobe_trace,light_gray)
region_trace<-c(region_trace,light_gray)
meta<-c(meta,pointer_text(name,region$role))
} else {
side<-region_side[region_side$key==paste(piece$hemisphere,piece$region),]
lobe_trace<-c(lobe_trace,lobe_colours[[lobe]])
region_trace<-c(region_trace,atlas$palette[[paste0(substr(piece$hemisphere,1,1),"h_",
piece$region)]])
meta<-c(meta,pointer_text(name,lobes$name[lobes$code==lobe],region$role,
paste0(number(side$area)," cm² of cortex, ",one(side$thickness),
" mm thick on average")))
}
}
colour_menu<-list(type="buttons",direction="right",x=0,y=1,xanchor="left",yanchor="bottom",
buttons=list(list(label="Lobes",method="restyle",
args=list(list(color=as.list(lobe_trace)))),
list(label="Regions",method="restyle",
args=list(list(color=as.list(region_trace))))))
p %>%
chart("The cortex of the average brain, by lobe",
paste(fsaverage,"Drag to turn, scroll to zoom."),
margin=list(t=100,b=80,l=0,r=0),note_y=0,note_shift=-40,scene=scene(),
updatemenus=list(colour_menu,view_menu)) %>%
finish_3d(lobe_trace,meta)The colors of the lobes follow the atlas, which counts the cingulate gyrus as a lobe of its own. The button Regions colors the 34 regions instead, and the pointer over a region gives its name, its lobe, what it does and its size. Each region does more than its one line says, and most of what we do takes many regions at once.
children<-data.frame(id=region_both$key,parent=region_both$lobe,label=region_both$name,
area=round(region_both$area,1),colour=lobe_colours[region_both$lobe])
# the insula is both a lobe and a region
children$id[children$id=="insula"]<-"insula region"
# a lobe's box holds exactly its regions' boxes
parents<-data.frame(id=lobe_both$key,parent="",label=lobe_both$name,
area=as.vector(tapply(children$area,children$parent,sum)[lobe_both$key]),
colour=lobe_colours[lobe_both$key])
p<-plot_ly(rbind(parents,children),type="treemap",ids=~id,parents=~parent,labels=~label,
values=~area,branchvalues="total",
marker=list(colors=~colour,line=list(color="white",width=1)),
texttemplate="%{label}<br>%{value:.0f} cm²",
hovertemplate=paste0("%{label}: %{value:.0f} cm², %{percentRoot:.1%} of the cortex",
"<extra></extra>"))
chart(p,"The area of each lobe and region, both hemispheres, cm²",
paste("FreeSurfer's fsaverage5, measured halfway through the cortex,",
"and the Desikan-Killiany atlas."),
uniformtext=list(minsize=10,mode="hide"),margin=list(t=50,b=50,l=0,r=0),note_y=0)Each box is as large as the area of its lobe or region; a click on a lobe opens its box.
deep_share<-100*sum(cortex$area[cortex$depth>5])/sum(cortex$area)
surface_share<-100*sum(cortex$area[cortex$depth<=2])/sum(cortex$area)
# the depth that half of the area of the cortex lies deeper than
by_depth<-order(cortex$depth)
half_depth<-cortex$depth[by_depth][which(cumsum(cortex$area[by_depth])>=sum(cortex$area)/2)[1]]
folded<-pial_area/wrap_area
deepest<-region_both[which.max(region_both$depth),]
shallowest<-region_both[which.min(region_both$depth),]
most_folded<-lobe_both[which.max(lobe_both$deep),]
least_folded<-lobe_both[which.min(lobe_both$deep),]Most of it. The outer surface of the cortex has 1.7 times the area of the wraps around the two hemispheres: 1,530 cm² against 926. Only 23% of the cortex lies within 2 mm of the wrap; 58% lies more than 5 mm under it, and half of it more than 7 mm under it. Deepest of all is the insula, 25 mm under the wrap on average, and the least deep the frontal pole, 0.6 mm.
# the depth in whole mm; the thickness in tenths of a mm, the labels of its color bar in mm
depth_max<-5*ceiling(quantile(cortex$depth,0.95)/5)
thickness_range<-round(2*quantile(cortex$thickness,c(0.02,0.98)))/2
thickness_ticks<-seq(10*thickness_range[[1]],10*thickness_range[[2]],by=5)
p<-plot_ly()
colours<-c()
meta<-c()
coloured<-c()
depth_values<-list()
thickness_values<-list()
for(k in seq_along(pieces)) {
piece<-pieces[[k]]
region<-regions[regions$code==piece$region,]
name<-paste0(region$name,", ",piece$hemisphere)
inflated<-as.matrix(points[piece$rows,c("inflated_x","inflated_y","inflated_z")])
if(piece$region=="medialwall") {
p<-add_mesh(p,inflated,piece$faces,name,flatshading=FALSE,lighting=lighting,
lightposition=above,showlegend=FALSE)
colours<-c(colours,light_gray)
meta<-c(meta,pointer_text(name,region$role))
} else {
depth<-round(points$depth[piece$rows])
p<-add_mesh(p,inflated,piece$faces,name,intensity=depth,colorscale=depth_scale,cmin=0,
cmax=depth_max,showscale=length(coloured)==0,flatshading=FALSE,
colorbar=list(title=list(text="mm under<br>the wrap"),len=0.5,thickness=12),
lighting=lighting,lightposition=above,showlegend=FALSE)
side<-region_side[region_side$key==paste(piece$hemisphere,piece$region),]
colours<-c(colours,NA)
meta<-c(meta,pointer_text(name,paste0(number(side$depth)," mm under the wrap on average, ",
percent(side$deep)," of it more than 5 mm"),
paste0(one(side$thickness)," mm thick on average")))
coloured<-c(coloured,k)
depth_values[[length(depth_values)+1]]<-depth
thickness_values[[length(thickness_values)+1]]<-round(10*points$thickness[piece$rows])
}
}
depth_button<-list(label="Depth",method="restyle",
args=list(list(intensity=depth_values,colorscale=list(depth_scale),cmin=0,
cmax=depth_max,colorbar.title.text="mm under<br>the wrap",
colorbar.tickmode="auto"),
coloured-1))
thickness_button<-list(label="Thickness",method="restyle",
args=list(list(intensity=thickness_values,colorscale=list(thickness_scale),
cmin=min(thickness_ticks),cmax=max(thickness_ticks),
colorbar.title.text="mm thick",colorbar.tickmode="array",
colorbar.tickvals=list(thickness_ticks),
colorbar.ticktext=list(one(thickness_ticks/10))),
coloured-1))
measure_menu<-list(type="buttons",direction="right",x=0,y=1,xanchor="left",yanchor="bottom",
buttons=list(depth_button,thickness_button))
p %>%
chart("The cortex blown up: how deep each point lies in the folded brain",
paste(fsaverage,"Grey: the medial wall."),
margin=list(t=100,b=80,l=0,r=0),note_y=0,note_shift=-40,scene=scene(),
updatemenus=list(measure_menu,view_menu)) %>%
finish_3d(colours,meta)This is the same cortex as in the first chart, blown up like a balloon until its folds open out, as FreeSurfer does to show all of it at once; each point keeps the color of its depth in the folded brain. The dark patches are the floors of the grooves, and the large dark field on the side is the insula, which the frontal and temporal lobes fold over. The button Thickness colors the cortex by its thickness instead, the subject of question 3.
bands<-cut(cortex$depth,c(0,2,10,20,Inf),c("Within 2 mm","2 to 10 mm","10 to 20 mm","Over 20 mm"),
right=FALSE)
band_area<-rbind(tapply(cortex$area,list(cortex$lobe,bands),sum),all=tapply(cortex$area,bands,sum))
band_area[is.na(band_area)]<-0
band_share<-100*prop.table(band_area,1)
band_share<-band_share[order(band_share[,"Over 20 mm"]+band_share[,"10 to 20 mm"]),]
lobe_label<-ifelse(rownames(band_share)=="all","<b>Whole cortex</b>",
lobes$name[match(rownames(band_share),lobes$code)])
p<-plot_ly()
for(b in colnames(band_share))
p<-add_bars(p,y=lobe_label,x=round(band_share[,b],1),name=b,orientation="h",
marker=list(color=band_colours[match(b,colnames(band_share))]),
hovertemplate=paste0("%{y}: %{x:.0f}% ",lower_first(b),"<extra></extra>"))
chart(p,"How deep each lobe lies under the wrap, % of its area",
paste("FreeSurfer's fsaverage5 and the Desikan-Killiany atlas.",
"The wrap: the convex hull of each hemisphere."),
barmode="stack",legend=c(legend_top,list(traceorder="normal")),margin=list(t=90,b=90),
note_y=-0.2,xaxis=list(title="",ticksuffix="%",range=c(0,100)),
yaxis=list(title="",categoryorder="array",categoryarray=lobe_label,automargin=TRUE))The lobes are not folded away alike: 100% of the insula lies more than 5 mm under the wrap, and 36% of the cingulate gyrus. The wrap reaches into no groove, so even the ridges of the cortex lie under it where a hemisphere curves inwards, as on its underside, between the temporal lobe and the frontal lobe.
mean_thickness<-weighted.mean(cortex$thickness,cortex$area)
by_thickness<-region_both[order(region_both$thickness),]
thinnest<-by_thickness[1,]
thickest<-by_thickness[nrow(by_thickness),]
thin_four<-by_thickness$key[1:4]
thick_four<-rev(by_thickness$key)[1:4]
# the regions of seeing and touch at the back of the brain, and those of memory and emotion at its
# front and bottom
senses<-c("pericalcarine","cuneus","lingual","lateraloccipital","postcentral","superiorparietal")
feelings<-c("temporalpole","entorhinal","parahippocampal","insula","rostralanteriorcingulate",
"caudalanteriorcingulate","medialorbitofrontal","frontalpole")
motor<-region_both[region_both$key=="precentral",]
touch<-region_both[region_both$key=="postcentral",]
left<-region_side[grepl("^left",region_side$key),]
right<-region_side[grepl("^right",region_side$key),]
region_both$left<-left$thickness[match(paste("left",region_both$key),left$key)]
region_both$right<-right$thickness[match(paste("right",region_both$key),right$key)]
side_gap<-max(abs(region_both$left-region_both$right))Between 1.8 and 4.5 mm, 2.7 on average. The four thinnest regions are the pericalcarine cortex, the cuneus, the postcentral gyrus and the superior parietal lobule, where sight and touch arrive, at the back of the brain. The four thickest are the temporal pole, the entorhinal cortex, the rostral anterior cingulate and the insula, at the front and at the bottom of the brain, where memory and emotion are handled. The two strips on either side of the central sulcus differ too: the precentral gyrus, which moves the body, is 2.6 mm thick, and the postcentral gyrus behind it, which feels it, 2.1 mm. The two hemispheres hardly differ: a region is at most 0.2 mm thicker on one side than on the other.
p<-plot_ly()
for(l in lobes$code) {
x<-region_both[region_both$lobe==l,]
p<-add_bars(p,data=x,y=~name,x=~round(thickness,2),name=lobes$name[lobes$code==l],
orientation="h",marker=list(color=lobe_colours[[l]]),
customdata=~paste0("left ",one(left),", right ",one(right)))
}
p<-style(p,hovertemplate="%{y}: %{x:.1f} mm (%{customdata})<extra></extra>")
chart(p,"The mean thickness of each region of the cortex, mm",
"fsaverage5 and the Desikan-Killiany atlas: the distance from the pial to the white surface.",
legend=legend_top,margin=list(t=100,b=70,l=10),note_y=-0.07,
xaxis=list(title="",ticksuffix=" mm"),
yaxis=list(title="",categoryorder="array",categoryarray=by_thickness$name,automargin=TRUE))The thickness here is the distance from each point of the outer surface of the cortex to the same point of its inner surface, close to the way FreeSurfer measures it (Fischl and Dale 2000). The button Thickness of the chart of question 2 shows it over the whole cortex.
cerebellum<-deep_list[deep_list$code=="cerebellum",]
cerebellum_share<-100*cerebellum$volume/brain_volume
largest<-deep_list[which.max(deep_list$volume),]
middle_kinds<-c("thalamus","caudate","putamen","pallidum","hippocampus","amygdala","accumbens")
middle_structures<-deep_list[deep_list$code%in%middle_kinds,]
largest_middle<-middle_structures[which.max(middle_structures$volume),]
hippocampus<-deep_list[deep_list$code=="hippocampus",]
amygdala<-deep_list[deep_list$code=="amygdala",]Twelve structures, and the largest by far is the cerebellum. The cerebellum takes up 155 cm³, 11% of the brain, which fills 1,409 cm³ without its spaces filled with fluid. Small as it is, it holds most of the brain’s nerve cells: about 69 of 86 billion, while the cerebral cortex and its white matter, 82% of the brain’s weight, hold only 19% of them (Azevedo et al. 2009). Of the structures in the middle of the brain, the thalamus is the largest, 8.6 cm³ on the left and 8.6 on the right; the hippocampus, where new memories are made, takes up 5.3 cm³ on each side, and the amygdala, of fear and emotion, 2.1.
p<-plot_ly()
for(h in names(hemispheres))
p<-add_mesh(p,coarse[[h]]$vertices,coarse[[h]]$faces,"Cortex",opacity=0.1,hoverinfo="skip",
lighting=glass_lighting,showlegend=FALSE)
colours<-c(glass_gray,glass_gray)
meta<-c(NA,NA)
for(k in seq_len(nrow(deep_list))) {
structure<-deep_list[k,]
shape<-deep_shapes[[structure$code]]
p<-add_mesh(p,shape$vertices,shape$faces,structure$name,flatshading=FALSE,lighting=lighting,
lightposition=above,showlegend=TRUE)
colours<-c(colours,deep_colours[[structure$code]])
meta<-c(meta,pointer_text(structure$name,structure$role,volume_words(structure)))
}
p %>%
chart("The structures under the cortex",
paste("FreeSurfer's segmentation of fsaverage (aseg.mgz), from fsbrain's test data.",
"A click on a name hides it."),
margin=list(t=60,b=80,l=0,r=0),note_y=0,note_shift=-40,
scene=scene(list(x=-1.25,y=0.75,z=0.3),list(x=c(0,0.8),y=c(0,1))),
legend=list(x=1,xanchor="right",y=0.95,itemsizing="constant"),
updatemenus=list(view_menu)) %>%
finish_3d(colours,meta)The glass is a coarse copy of the cortex. The structures are traced from FreeSurfer’s labeled cubes of 1 mm and smoothed a little. Between them lie the ventricles, the subject of the next question.
Fluid: 46.4 cm³ of it, in four ventricles. The brain is hollow in the middle. Its two lateral ventricles, one in each hemisphere, arch from the front of the brain back over the thalamus and then down into the temporal lobe; they hold 22.0 cm³ on the left and 20.2 on the right. Both open into the narrow third ventricle, between the two halves of the thalamus (1.9 cm³), which drains through a thin channel, the aqueduct, into the fourth ventricle, between the brain stem and the cerebellum (2.2 cm³); from there the fluid flows out around the brain and the spinal cord. Most of it is made by the choroid plexus, a fringe of small blood vessels in the ventricles, and it is renewed about four times a day. A living adult has about 150 ml of it, 25 ml of which is in the ventricles (Sakka et al. 2011); the ventricles of the average brain hold more, and like all its sizes theirs are not those of any one head.
p<-plot_ly()
for(h in names(hemispheres))
p<-add_mesh(p,coarse[[h]]$vertices,coarse[[h]]$faces,"Cortex",opacity=0.1,hoverinfo="skip",
lighting=glass_lighting,showlegend=FALSE)
colours<-c(glass_gray,glass_gray)
meta<-c(NA,NA)
for(k in seq_len(nrow(ventricle_list))) {
space<-ventricle_list[k,]
shape<-ventricle_shapes[[space$code]]
p<-add_mesh(p,shape$vertices,shape$faces,space$name,flatshading=FALSE,lighting=lighting,
lightposition=above,showlegend=TRUE)
colours<-c(colours,ventricle_colours[[space$code]])
meta<-c(meta,pointer_text(space$name,space$role,volume_words(space)))
}
p %>%
chart("The ventricles, the hollows of the brain",
paste("FreeSurfer's segmentation of fsaverage (aseg.mgz), from fsbrain's test data.",
"A click on a name hides it."),
margin=list(t=60,b=80,l=0,r=0),note_y=0,note_shift=-40,
scene=scene(list(x=-1.25,y=0.75,z=0.3),list(x=c(0,0.8),y=c(0,1))),
legend=list(x=1,xanchor="right",y=0.95,itemsizing="constant"),
updatemenus=list(view_menu)) %>%
finish_3d(colours,meta)FreeSurfer’s segmentation does not label the aqueduct, so the third and the fourth ventricle look apart here.
longest<-tract_list[which.max(tract_list$length),]
shortest<-tract_list[which.min(tract_list$length),]
arcuate<-tract_list[tract_list$code=="af"&tract_list$side=="left",]
group_count<-table(factor(tract_list$group,levels=names(groups)))
cerebellar<-if(group_count[["cerebellar"]]==1) "one carries signals into the cerebellum" else
paste(group_count[["cerebellar"]],"carry signals into the cerebellum")42 bundles in this atlas, from 5 to 15 cm long. Of them, 9 cross from one hemisphere to the other (the eight parts of the corpus callosum and the anterior commissure), 16 link areas within a hemisphere, 8 run between the cortex and the thalamus or the spinal cord, 8 belong to the circuits of memory and emotion, and one carries signals into the cerebellum. The arcuate fasciculus, which joins the speech areas at the front and at the back of the brain, is 114 mm long on the left. The longest of all is the corticospinal tract, 149 mm, from the motor cortex down to the bottom of the brain stem, where the atlas ends and the tract goes on down the spinal cord; the shortest the acoustic radiation, 52 mm.
p<-plot_ly()
for(h in names(hemispheres))
p<-add_mesh(p,coarse[[h]]$vertices,coarse[[h]]$faces,"Cortex",opacity=0.08,hoverinfo="skip",
lighting=glass_lighting,showlegend=FALSE)
colours<-c(glass_gray,glass_gray)
meta<-c(NA,NA)
shown<-c()
for(k in order(match(tract_list$group,names(groups)),tract_list$code)) {
tract<-tract_list[k,]
line<-as.data.frame(round(10*tract_points[[k]]))
p<-add_trace(p,data=line,x=~V1,y=~V2,z=~V3,type="scatter3d",mode="lines",
name=groups[[tract$group]],legendgroup=tract$group,
showlegend=!tract$group%in%shown,
line=list(color=group_colours[[tract$group]],width=6))
shown<-c(shown,tract$group)
side<-if(tract$side=="middle") "" else paste0(", ",tract$side)
colours<-c(colours,NA)
meta<-c(meta,pointer_text(paste0(tract$name,side),tract$role,
paste0(number(tract$length)," mm long")))
}
p %>%
chart("The tracts of white matter, by kind",
"TRACULA's atlas of white-matter tracts, from ggseg.formats. A click on a kind hides it.",
margin=list(t=120,b=80,l=0,r=0),note_y=0,note_shift=-40,
scene=scene(list(x=-1.25,y=0.75,z=0.3)),legend=c(legend_top,list(itemsizing="constant")),
updatemenus=list(view_menu)) %>%
finish_3d(colours,meta)Each line is the middle of a bundle of fibers several millimeters thick, which fans out where it reaches the cortex. The pointer over a line names the tract, says what it carries and how long it is.
The brain is a large sheet packed into a small skull, hollow in the middle and wired across.
What this does not show. The brain is an average of many brains, and smoother than any one of them: averaging blurs the folds, so a real brain has more area and deeper folds than this one, and its parts differ in size and shape from person to person. The regions of the atlas follow the folds, not what the cortex does, and their roles are simplified: each region does more than one thing, and most tasks use many regions. The thickness and the depth are measured on the average surfaces, not averaged over people. The structures under the cortex and the ventricles are traced from FreeSurfer’s labeled cubes of 1 mm and smoothed a little; the tracts come from an atlas with a frame of its own, are laid on the volume as shown under The data, and are the middle lines of their bundles. The volumes are those of the average brain, whose size is set by the template it was laid on, not by any one head.
For how the brain can be fooled by what the eyes see, see Illusions in R.
The average brain, the atlas of its regions, its segmentation and the atlas of its tracts come from FreeSurfer. The surfaces drawn on this page are modified from FreeSurfer’s: they are turned and moved into one frame, cut into regions, simplified and, for the structures under the cortex and the ventricles, traced from the labeled volume; they are not FreeSurfer’s original files. The surfaces of the cortex and the atlases come from the R packages ggseg.formats and ggseg.meshes, © 2026 their authors, under the MIT license, and the copy of the segmentation from the server of the fsbrain package. The idea of a brain that turns under the mouse comes from Plotly’s MRI Reconstruction app.
All or portions of this licensed product (such portions are the “Software”) have been obtained under license from The General Hospital Corporation “MGH” and are subject to the following terms and conditions:
PART B. DOWNLOADING AGREEMENT - License from MGH with Right to Sublicense
("Software License").
1. As used in this Software License, "you" means the individual
downloading and/or using, reproducing, modifying, displaying and/or
distributing the Software and the institution or entity which
employs or is otherwise affiliated with such individual in
connection therewith. The General Hospital Corporation ("MGH")
hereby grants you, with right to sublicense, with
respect to MGH's rights in the software, and data, if any,
which is the subject of this Software License (collectively, the
"Software"), a royalty-free, non-exclusive license to use,
reproduce, make derivative works of, display and distribute the
Software, provided that:
(a) you accept and adhere to all of the terms and conditions of this
Software License;
(b) in connection with any copy of or sublicense of all or any portion
of the Software, all of the terms and conditions in this Software
License shall appear in and shall apply to such copy and such
sublicense, including without limitation all source and executable
forms and on any user documentation, prefaced with the following
words: "All or portions of this licensed product (such portions are
the "Software") have been obtained under license from The General Hospital
Corporation "MGH" and are subject to the following terms and
conditions:"
(c) you preserve and maintain all applicable attributions, copyright
notices and licenses included in or applicable to the Software;
(d) modified versions of the Software must be clearly identified and
marked as such, and must not be misrepresented as being the original
Software; and
(e) you consider making, but are under no obligation to make, the
source code of any of your modifications to the Software freely
available to others on an open source basis.
2. The license granted in this Software License includes without
limitation the right to (i) incorporate the Software into
proprietary programs (subject to any restrictions applicable to
such programs), (ii) add your own copyright statement to your
modifications of the Software, and (iii) provide additional or
different license terms and conditions in your sublicenses of
modifications of the Software; provided that in each case your use,
reproduction or distribution of such modifications otherwise
complies with the conditions stated in this Software License.
3. This Software License does not grant any rights with respect to
third party software, except those rights that MGH has been
authorized by a third party to grant to you, and accordingly you
are solely responsible for (i) obtaining any permissions from third
parties that you need to use, reproduce, make derivative works of,
display and distribute the Software, and (ii) informing your
sublicensees, including without limitation your end-users, of their
obligations to secure any such required permissions.
4. The Software has been designed for research purposes only and has
not been reviewed or approved by the Food and Drug Administration
or by any other agency. YOU ACKNOWLEDGE AND AGREE THAT CLINICAL
APPLICATIONS ARE NEITHER RECOMMENDED NOR ADVISED. Any
commercialization of the Software is at the sole risk of the party
or parties engaged in such commercialization. You further agree to
use, reproduce, make derivative works of, display and distribute
the Software in compliance with all applicable governmental laws,
regulations and orders, including without limitation those relating
to export and import control.
5. The Software is provided "AS IS" and neither MGH nor any
contributor to the software (each a "Contributor") shall have any
obligation to provide maintenance, support, updates, enhancements
or modifications thereto. MGH AND ALL CONTRIBUTORS SPECIFICALLY
DISCLAIM ALL EXPRESS AND IMPLIED WARRANTIES OF ANY KIND INCLUDING,
BUT NOT LIMITED TO, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR
A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
MGH OR ANY CONTRIBUTOR BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ARISING IN ANY WAY
RELATED TO THE SOFTWARE, EVEN IF MGH OR ANY CONTRIBUTOR HAS
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. TO THE MAXIMUM
EXTENT NOT PROHIBITED BY LAW OR REGULATION, YOU FURTHER ASSUME ALL
LIABILITY FOR YOUR USE, REPRODUCTION, MAKING OF DERIVATIVE WORKS,
DISPLAY, LICENSE OR DISTRIBUTION OF THE SOFTWARE AND AGREE TO
INDEMNIFY AND HOLD HARMLESS MGH AND ALL CONTRIBUTORS FROM AND
AGAINST ANY AND ALL CLAIMS, SUITS, ACTIONS, DEMANDS AND JUDGMENTS
ARISING THEREFROM.
6. None of the names, logos or trademarks of MGH or any of
MGH's affiliates or any of the Contributors, or any funding
agency, may be used to endorse or promote products produced in
whole or in part by operation of the Software or derived from or
based on the Software without specific prior written permission
from the applicable party.
7. Any use, reproduction or distribution of the Software which is not
in accordance with this Software License shall automatically revoke
all rights granted to you under this Software License and render
Paragraphs 1 and 2 of this Software License null and void.
8. This Software License does not grant any rights in or to any
intellectual property owned by MGH or any Contributor except
those rights expressly granted hereunder.
The whole agreement is on FreeSurfer’s website.
Rendered with R 4.6.2 · plotly · ggseg.formats · ggseg.meshes · freesurferformats · misc3d · geometry
---
title: "Inside the Human Brain: A 3D Map of Its Parts and Wiring"
description: "The average human brain in 3D, drawn with plotly from FreeSurfer's fsaverage: the lobes and the 34 regions of the cortex in each hemisphere and what they do, how much of the cortex is hidden in the folds and how thick it is, the structures deep under it, from the thalamus to the cerebellum, the hollows filled with fluid in its middle, and 42 tracts of white matter that wire them together."
author: ""
---
```{r setup, include=FALSE}
directory<-""
if(rstudioapi::isAvailable())
directory<-paste0(dirname(rstudioapi::getActiveDocumentContext()$path),"/")
source(paste0(directory,"R/code_options.R"))
```
## What is this?
Plotly's [MRI Reconstruction](https://brain-viewer.plotly.app/) app shows a human brain that turns under the mouse ([its code](https://github.com/plotly/dash-sample-apps/tree/master/apps/dash-brain-viewer)). This data story draws such a brain with plotly in R and adds its anatomy: the names of its parts, what each part does, how large it is, and how the parts are wired together. Six questions:
1. **What are the parts of the cortex?**
2. **How much of the cortex is hidden in the folds?**
3. **Where is the cortex thickest?**
4. **What lies under the cortex?**
5. **What fills the hollows inside the brain?**
6. **How are the parts wired together?**
The brain is **fsaverage**, the average brain of FreeSurfer, a widely used program that measures the cortex on MRI scans: the brains of many adults, laid over each other fold to fold ([Fischl et al. 1999](https://doi.org/10.1002/(SICI)1097-0193(1999)8%3A4%3C272%3A%3AAID-HBM10%3E3.0.CO%3B2-4)). Its parts come from three sources: the **Desikan–Killiany atlas** of the cortex, with 34 regions in each hemisphere, bounded mostly by the folds ([Desikan et al. 2006](https://doi.org/10.1016/j.neuroimage.2006.01.021)); FreeSurfer's **segmentation** of the same brain, a volume of cubes of 1 mm each labeled with the structure it lies in ([Fischl et al. 2002](https://doi.org/10.1016/S0896-6273(02)00569-X)), from which the page draws the structures under the cortex and the ventricles; and **TRACULA**, an atlas of 42 bundles of white matter traced from diffusion MRI ([Yendiki et al. 2011](https://doi.org/10.3389/fninf.2011.00023); [Maffei et al. 2021](https://doi.org/10.1016/j.neuroimage.2021.118706)). The cortex, its atlas and TRACULA come with the R packages ggseg.meshes and ggseg.formats ([Mowinckel and Vidal-Piñeiro 2020](https://doi.org/10.1177/2515245920928009)); the segmentation, 365 KB, is downloaded once from the server of the fsbrain package ([Schäfer and Ecker 2020](https://doi.org/10.1101/2020.09.18.302935)).
**The words of this page:**
- the **cortex** is the outer layer of the brain: a folded sheet of gray matter a few millimeters thick, made of the bodies of nerve cells. Its ridges are **gyri** (one *gyrus*), its grooves **sulci** (one *sulcus*);
- the brain has two **hemispheres**, left and right (the brain's own left and right), and the cortex of each is divided into **lobes**;
- **white matter** is made of the long fibers of nerve cells, wrapped in a fatty sheath; a **tract** is a bundle of them that links two parts of the brain;
- the **ventricles** are the hollows inside the brain, filled with a clear fluid (*cerebrospinal fluid*) that also bathes the brain and the spinal cord;
- the **wrap** is the smallest shape around a hemisphere that has no dents (its *convex hull*): what a sheet of cling film, pulled tight around it, would cover.
---
## Packages
```{r packages}
# install.packages(c("plotly","ggseg.formats","ggseg.meshes","freesurferformats","misc3d",
# "geometry"))
library(plotly)
```
```{r labels}
# short labels of numbers, lists and shifts for the text
number<-function(x) {
result<-format(round(x),big.mark=",",trim=TRUE)
return(result)
}
one<-function(x) {
result<-format(round(x,1),nsmall=1,trim=TRUE)
return(result)
}
percent<-function(x) {
result<-paste0(round(x),"%")
return(result)
}
and_list<-function(x) {
result<-if(length(x)<2) paste(x) else paste(paste(x[-length(x)],collapse=", "),"and",
x[length(x)])
return(result)
}
count_words<-function(n) {
words<-c("one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve")
result<-if(n<=12) words[n] else number(n)
return(result)
}
upper_first<-function(x) {
result<-paste0(toupper(substr(x,1,1)),substring(x,2))
return(result)
}
lower_first<-function(x) {
result<-paste0(tolower(substr(x,1,1)),substring(x,2))
return(result)
}
# "24.0 mm further forward" or "3.5 mm further back"
shift_words<-function(x,positive,negative) {
result<-paste(one(abs(x)),"mm",if(x>=0) positive else negative)
return(result)
}
```
## The data
### The cortex
```{r cortex}
# a surface of the cortex of one hemisphere of fsaverage5, 10,242 points joined in 20,480 triangles.
# ggseg.meshes keeps it turned a quarter round, with x from the back to the front: here x runs from
# left to right, y from the back to the front and z from the bottom to the top, in mm
read_surface<-function(hemisphere,surface) {
mesh<-ggseg.meshes::get_cortical_mesh(hemisphere,surface)
vertices<-cbind(x=-mesh$vertices$y,y=mesh$vertices$x,z=mesh$vertices$z)
result<-list(vertices=vertices,faces=as.matrix(mesh$faces))
return(result)
}
# the area of each triangle of a surface, in mm²
triangle_area<-function(vertices,faces) {
a<-vertices[faces[,2],]-vertices[faces[,1],]
b<-vertices[faces[,3],]-vertices[faces[,1],]
result<-sqrt((a[,2]*b[,3]-a[,3]*b[,2])^2+(a[,3]*b[,1]-a[,1]*b[,3])^2+
(a[,1]*b[,2]-a[,2]*b[,1])^2)/2
return(result)
}
# the Desikan-Killiany atlas: the points of each region (numbered from 0), and the lobe of each
atlas<-ggseg.formats::dk()
atlas_points<-atlas$data$vertices
atlas_lobes<-unique(as.data.frame(atlas$core)[,c("label","lobe")])
hemispheres<-c(lh="left",rh="right")
faces<-list()
points<-data.frame()
pial_area<-0
for(h in names(hemispheres)) {
pial<-read_surface(h,"pial")
white<-read_surface(h,"white")$vertices
middle<-read_surface(h,"midthickness")$vertices
# the inflated surface comes from ggseg.formats, already in this frame but with each hemisphere
# around x = 0: they move apart, their inner sides 4 mm from the middle
inflated<-as.matrix(ggseg.formats::get_brain_mesh(h,"inflated")$vertices)
inflated[,1]<-if(h=="lh") inflated[,1]-max(inflated[,1])-4 else inflated[,1]-min(inflated[,1])+4
faces[[h]]<-pial$faces
# the region of each point; the points of no region are the medial wall, where the hemisphere is
# cut away from the structures under it (the atlas calls a part of it "corpus callosum")
region<-rep("medialwall",nrow(pial$vertices))
for(k in grep(paste0("^",h,"_"),atlas_points$label))
region[atlas_points$vertices[[k]]+1]<-sub("^[lr]h_","",atlas_points$label[k])
# the area of the cortex around each point, measured halfway through its thickness: a third of
# each triangle that the point is a corner of
triangles<-triangle_area(middle,pial$faces)
area<-as.vector(rowsum(rep(triangles/3,3),as.vector(pial$faces)))
pial_area<-pial_area+sum(triangle_area(pial$vertices,pial$faces))
# the thickness at a point: the distance from the outer (pial) surface of the cortex to the inner
# (white) one, which have the same points
points<-rbind(points,data.frame(hemisphere=hemispheres[[h]],region=region,pial$vertices,
inflated_x=inflated[,1],inflated_y=inflated[,2],
inflated_z=inflated[,3],middle_x=middle[,1],
middle_y=middle[,2],middle_z=middle[,3],area=area,
thickness=sqrt(rowSums((pial$vertices-white)^2))))
}
points$lobe<-atlas_lobes$lobe[match(paste0(substr(points$hemisphere,1,1),"h_",points$region),
atlas_lobes$label)]
xyz<-as.matrix(points[,c("x","y","z")])
```
### The wrap
```{r wrap}
# the wrap of each hemisphere: the convex hull of its points. Each row of hull$normals is the plane
# of one of the hull's triangles, a x + b y + c z + d = 0, with (a, b, c) pointing outwards. The
# depth of a point under the wrap is its distance to the nearest of those planes, worked out for
# 2,000 points at a time to keep the table of distances small
points$depth<-NA
wrap_area<-0
for(h in hemispheres) {
rows<-which(points$hemisphere==h)
hull<-geometry::convhulln(xyz[rows,],output.options="n FA")
wrap_area<-wrap_area+hull$area
for(block in split(rows,ceiling(seq_along(rows)/2000))) {
distance<-xyz[block,]%*%t(hull$normals[,1:3])+
matrix(hull$normals[,4],length(block),nrow(hull$normals),byrow=TRUE)
points$depth[block]<-apply(-distance,1,min)
}
}
```
### The regions and the lobes
```{r regions}
# the names of the regions and of the lobes and what they do, simplified from textbooks (see the
# sources); "medialwall" is not a region of the cortex
regions<-read.csv(sep="|",text="code|name|role
bankssts|Superior temporal sulcus|Its banks: making sense of speech, faces and movements
caudalanteriorcingulate|Caudal anterior cingulate|Noticing mistakes and conflicts, and pain
caudalmiddlefrontal|Caudal middle frontal gyrus|Moving the eyes (frontal eye field), attention
cuneus|Cuneus|Seeing: visual areas for the lower half of the view
entorhinal|Entorhinal cortex|The gateway to the hippocampus: memory and finding the way
fusiform|Fusiform gyrus|Recognising faces, bodies and written words
inferiorparietal|Inferior parietal lobule|Reading, numbers and meaning (the angular gyrus)
inferiortemporal|Inferior temporal gyrus|Recognising objects by sight
isthmuscingulate|Isthmus of the cingulate|Memory and finding the way (the retrosplenial cortex)
lateraloccipital|Lateral occipital cortex|Seeing shapes, objects and motion
lateralorbitofrontal|Lateral orbitofrontal cortex|Learning from rewards and losses
lingual|Lingual gyrus|Seeing: visual areas for the upper half of the view
medialorbitofrontal|Medial orbitofrontal cortex|The value of things, and choosing between them
middletemporal|Middle temporal gyrus|The meanings of words and things
parahippocampal|Parahippocampal gyrus|Recognising places and scenes, and memory
paracentral|Paracentral lobule|Moving and feeling the legs and feet
parsopercularis|Pars opercularis|Speaking: part of Broca's area, mostly on the left
parsorbitalis|Pars orbitalis|The meanings of words and sentences
parstriangularis|Pars triangularis|Language: part of Broca's area, mostly on the left
pericalcarine|Pericalcarine cortex|Seeing: the primary visual cortex, first to get the eyes' signals
postcentral|Postcentral gyrus|Touch and the sense of the body: the primary somatosensory cortex
posteriorcingulate|Posterior cingulate|Remembering, thinking about oneself and daydreaming
precentral|Precentral gyrus|Moving the body: the primary motor cortex
precuneus|Precuneus|Imagining scenes, remembering, and the self in space
rostralanteriorcingulate|Rostral anterior cingulate|Emotions, and keeping them in check
rostralmiddlefrontal|Rostral middle frontal gyrus|Planning, holding things in mind, self-control
superiorfrontal|Superior frontal gyrus|Planning movements (supplementary motor area), thinking
superiorparietal|Superior parietal lobule|Where things are, and reaching for them
superiortemporal|Superior temporal gyrus|Hearing and understanding speech (Wernicke's area)
supramarginal|Supramarginal gyrus|The sounds of words, and using tools and gestures
frontalpole|Frontal pole|The most abstract planning: keeping other options in mind
temporalpole|Temporal pole|Knowing people and things, and emotion
transversetemporal|Transverse temporal gyrus|Hearing: the primary auditory cortex (Heschl's gyrus)
insula|Insula|Feeling the inside of the body, taste, and disgust
medialwall|Medial wall|Not cortex: where the hemisphere is cut away from the structures under it")
lobes<-read.csv(sep="|",text="code|name|role
frontal|Frontal lobe|Planning, deciding, speaking and moving
parietal|Parietal lobe|Touch, and where things are
temporal|Temporal lobe|Hearing, language, memory and recognising things
occipital|Occipital lobe|Seeing
cingulate|Cingulate gyrus|Emotion, attention and memory
insula|Insula|Feelings from inside the body, and taste")
# a region's (or a lobe's) area in cm², and its thickness and its depth under the wrap in mm,
# weighted by the area around each point; deep: the share of its area more than 5 mm under the wrap
summarise_cortex<-function(x,group) {
totals<-rowsum(cbind(area=x$area,thickness=x$thickness*x$area,depth=x$depth*x$area,
deep=(x$depth>5)*x$area),group)
result<-data.frame(key=rownames(totals),area=totals[,"area"]/100,
thickness=totals[,"thickness"]/totals[,"area"],
depth=totals[,"depth"]/totals[,"area"],
deep=100*totals[,"deep"]/totals[,"area"])
return(result)
}
cortex<-points[!points$region%in%c("medialwall","corpuscallosum"),]
region_both<-summarise_cortex(cortex,cortex$region)
region_both$lobe<-cortex$lobe[match(region_both$key,cortex$region)]
region_both$name<-regions$name[match(region_both$key,regions$code)]
region_side<-summarise_cortex(cortex,paste(cortex$hemisphere,cortex$region))
lobe_both<-summarise_cortex(cortex,cortex$lobe)
lobe_both$name<-lobes$name[match(lobe_both$key,lobes$code)]
lobe_both$share<-100*lobe_both$area/sum(lobe_both$area)
```
### The structures under the cortex and the ventricles
```{r deep}
# FreeSurfer's segmentation of fsaverage (aseg.mgz): a volume of 256 × 256 × 256 cubes of 1 mm, each
# labeled with the structure it lies in. The server of the fsbrain package keeps a copy (365 KB);
# the page keeps its download, and the checksum makes sure that it is the file the page was written
# for
download_file<-function(url,file,tries=3) {
for(k in seq_len(tries)) {
done<-tryCatch(download.file(url,file,mode="wb",quiet=TRUE)==0,error=function(e) FALSE)
if(done)
return(invisible(file))
Sys.sleep(10)
}
stop("Could not download ",url)
}
cache<-tools::R_user_dir("illustration","cache")
dir.create(cache,recursive=TRUE,showWarnings=FALSE)
aseg_file<-file.path(cache,"fsaverage_aseg.mgz")
aseg_url<-"https://rcmd.org/projects/nitestdata/subjects_dir/fsaverage/mri/aseg.mgz"
if(!file.exists(aseg_file))
download_file(aseg_url,aseg_file)
stopifnot(unname(tools::md5sum(aseg_file))=="b4a8f385370e5c831cdbe2f2a00d2d51")
aseg<-freesurferformats::read.fs.mgh(aseg_file,with_header=TRUE)
labels<-aseg$data[,,,1]
# the cubes of each label (0 to 255), counted: 1,000 cubes of 1 mm make a cm³
cubes<-tabulate(as.vector(labels)+1,nbins=256)
# from a cube (its column, row and slice, numbered from 1) to mm in the frame of the cortex, and
# the label of the cube at a point
voxel_matrix<-freesurferformats::mghheader.vox2ras.tkreg(aseg$header)
voxel_xyz<-function(ijk) {
result<-(cbind(ijk-1,1)%*%t(voxel_matrix))[,1:3,drop=FALSE]
return(result)
}
label_at<-function(xyz) {
ijk<-round((cbind(xyz,1)%*%t(solve(voxel_matrix)))[,1:3,drop=FALSE])+1
inside<-rowSums(ijk>=1&ijk<=256)==3
result<-rep(NA,nrow(xyz))
result[inside]<-labels[ijk[inside,,drop=FALSE]]
return(result)
}
# the volume and the surfaces should lie in the same frame: the points halfway through the cortex
# should fall in cubes labeled cortex (3 on the left, 42 on the right). The share of them that do,
# with the volume where it is and moved by up to 2 mm in each direction
on_cortex<-function(shift,middle,expected) {
result<-100*mean(label_at(sweep(middle,2,shift,"+"))==expected,na.rm=TRUE)
return(result)
}
middle<-as.matrix(points[,c("middle_x","middle_y","middle_z")])
moves<-expand.grid(dx=-2:2,dy=-2:2,dz=-2:2)
moves$share<-apply(moves,1,on_cortex,middle=middle,
expected=ifelse(points$hemisphere=="left",3,42))
in_place<-moves$share[moves$dx==0&moves$dy==0&moves$dz==0]
```
The volume lies in the frame of the cortex: `r percent(in_place)` of the points halfway through the cortex fall in cubes labeled cortex (most of the others lie on the medial wall or at the edge of the cortex), `r if(in_place>=max(moves$share)) "and no move of up to 2 mm in any direction does better" else paste0("against ",percent(max(moves$share))," at best when the volume is moved by up to 2 mm")`.
```{r deep_lists}
# the structures under the cortex and the ventricles: their names, the labels of their cubes on the
# left, on the right or in the middle, and what they do
deep_list<-read.csv(sep="|",colClasses="character",text="code|name|left|right|middle|role
cerebellum|Cerebellum|7 8|46 47||Balance, coordination and the timing of movements
brainstem|Brain stem|||16|Breathing, heartbeat, sleep and waking; joins the brain to the spinal cord
thalamus|Thalamus|10|49||The relay station of the senses (all but smell) on the way to the cortex
caudate|Caudate nucleus|11|50||Basal ganglia: learning, goals and habits
putamen|Putamen|12|51||Basal ganglia: movement and habits
pallidum|Globus pallidus|13|52||Basal ganglia: lets movements go ahead or holds them back
hippocampus|Hippocampus|17|53||Making new memories, and finding the way
amygdala|Amygdala|18|54||Emotion, fear, and noticing danger
accumbens|Nucleus accumbens|26|58||Reward and motivation
ventraldc|Ventral diencephalon|28|60||The hypothalamus and nuclei around it: hunger, sleep, hormones
callosum|Corpus callosum|||251 252 253 254 255|The bridge of nerve fibres between the hemispheres
chiasm|Optic chiasm|||85|Where the optic nerves cross: each hemisphere sees the opposite half")
ventricle_list<-read.csv(sep="|",colClasses="character",text="code|name|left|right|middle|role
lateral|Lateral ventricles|4 5|43 44||One in each hemisphere, arching back into the temporal lobe
third|Third ventricle|||14|A narrow slit between the two halves of the thalamus
fourth|Fourth ventricle|||15|Between the brain stem and the cerebellum; the fluid flows out from it
choroid|Choroid plexus|31|63||Small blood vessels in the ventricles that make most of the fluid")
# the volume of a list of labels, in cm³, and of each structure on each side
label_volume<-function(numbers) {
result<-if(numbers=="") 0 else sum(cubes[as.integer(strsplit(numbers," ")[[1]])+1])/1000
return(result)
}
for(side in c("left","right","middle")) {
deep_list[[paste0(side,"_volume")]]<-sapply(deep_list[[side]],label_volume,USE.NAMES=FALSE)
ventricle_list[[paste0(side,"_volume")]]<-sapply(ventricle_list[[side]],label_volume,
USE.NAMES=FALSE)
}
deep_list$volume<-deep_list$left_volume+deep_list$right_volume+deep_list$middle_volume
ventricle_list$volume<-ventricle_list$left_volume+ventricle_list$right_volume+
ventricle_list$middle_volume
# the brain: every labeled cube but those of the spaces filled with fluid (the ventricles and the
# fluid around the brain stem)
fluid<-c(4,5,14,15,24,43,44,72)
brain_volume<-(sum(cubes[-1])-sum(cubes[fluid+1]))/1000
```
### The tracts
```{r tracts}
tracts<-ggseg.formats::tracula()$data$centerlines
# the tracts come in a frame of their own, and mirrored: those of the left hemisphere ("lh.") lie
# at positive x. Mirrored back, they are laid on the volume where most of their points fall in
# white matter (2, 41, 7, 46, 77) or in the deep structures that they cross (the brain stem 16, the
# ventral diencephalon 28 and 60, the corpus callosum 251 to 255, the thalamus 10 and 49, the optic
# chiasm 85): first every 1 mm up to 30 mm forwards or backwards and up or down, then every 0.5 mm
# around the best, from side to side too
tract_points<-lapply(tracts$points,function(m) cbind(-m[,1],m[,2],m[,3]))
all_points<-do.call(rbind,tract_points)
white<-c(2,41,7,46,77,16,28,60,251:255,10,49,85)
in_white<-function(shift,xyz) {
result<-100*mean(label_at(sweep(xyz,2,shift,"+"))%in%white)
return(result)
}
first_moves<-expand.grid(dx=0,dy=-30:30,dz=-30:30)
first_moves$share<-apply(first_moves,1,in_white,xyz=all_points)
start<-first_moves[which.max(first_moves$share),]
moves_near<-expand.grid(dx=seq(-2,2,by=0.5),dy=start$dy+seq(-1.5,1.5,by=0.5),
dz=start$dz+seq(-1.5,1.5,by=0.5))
moves_near$share<-apply(moves_near,1,in_white,xyz=all_points)
tract_fit<-moves_near[which.max(moves_near$share),]
unmoved<-in_white(c(0,0,0),all_points)
tract_shift<-c(tract_fit$dx,tract_fit$dy,tract_fit$dz)
tract_points<-lapply(tract_points,function(m) sweep(m,2,tract_shift,"+"))
# each tract: its side, its code without the side ("af", "cc.genu") and its length in mm
code<-sub("\\.bbr\\.prep$","",tracts$label)
tract_list<-data.frame(side=ifelse(grepl("^lh\\.",code),"left",
ifelse(grepl("^rh\\.",code),"right","middle")),
code=sub("^[lr]h\\.","",code))
tract_list$length<-sapply(tract_points,function(m) sum(sqrt(rowSums(diff(m)^2))))
```
Mirrored and moved `r shift_words(tract_fit$dy,"forwards","backwards")`, `r shift_words(tract_fit$dz,"upwards","downwards")` and `r shift_words(tract_fit$dx,"to the right","to the left")`, `r percent(tract_fit$share)` of the points of the tracts fall in white matter or in the deep structures that they cross, the most for any move tried; where they come, `r percent(unmoved)` do.
```{r names}
# the tracts: their names, their group and what they do
tract_names<-read.csv(sep="|",text="code|name|group|role
cc.rostrum|Corpus callosum: rostrum|commissural|Links the orbitofrontal cortex of the two sides
cc.genu|Corpus callosum: genu|commissural|Links the prefrontal cortex of the two hemispheres
cc.bodypf|Corpus callosum: body, prefrontal|commissural|Links the prefrontal cortex of the two sides
cc.bodypm|Corpus callosum: body, premotor|commissural|Links the premotor cortex of the two sides
cc.bodyc|Corpus callosum: body, central|commissural|Links the motor and touch strips of both sides
cc.bodyp|Corpus callosum: body, parietal|commissural|Links the parietal lobes
cc.bodyt|Corpus callosum: body, temporal|commissural|Links the temporal lobes
cc.splenium|Corpus callosum: splenium|commissural|Links the occipital lobes
acomm|Anterior commissure|commissural|Links the two temporal lobes, and smell
af|Arcuate fasciculus|association|Language: links the speech areas at the front and at the back
slf1|Superior longitudinal fasciculus I|association|Movement and attention, along the top
slf2|Superior longitudinal fasciculus II|association|Attention to where things are
slf3|Superior longitudinal fasciculus III|association|Language and gestures, along the side
ilf|Inferior longitudinal fasciculus|association|Recognising what is seen: occipital to temporal
mlf|Middle longitudinal fasciculus|association|Hearing and language: temporal to parietal
emc|Extreme capsule|association|Language: links the temporal lobe with the frontal lobe
fat|Frontal aslant tract|association|Starting to speak and act: links the top of the frontal lobe
uf|Uncinate fasciculus|limbic|Emotion and memory: temporal pole to orbitofrontal cortex
cbd|Cingulum, upper part|limbic|Attention and emotion: runs inside the cingulate gyrus
cbv|Cingulum, lower part|limbic|Memory: links the cingulate gyrus with the hippocampal region
fx|Fornix|limbic|Memory: carries signals out of the hippocampus
cst|Corticospinal tract|projection|Moving: from the motor cortex down to the spinal cord
atr|Anterior thalamic radiation|projection|Links the thalamus with the front of the brain
or|Optic radiation|projection|Seeing: from the thalamus to the visual cortex
ar|Acoustic radiation|projection|Hearing: from the thalamus to the auditory cortex
mcp|Middle cerebellar peduncle|cerebellar|Carries signals from the cortex, through the pons")
groups<-c(commissural="Commissural: across the hemispheres",
association="Association: within a hemisphere",
projection="Projection: cortex to thalamus and spinal cord",
limbic="Limbic: memory and emotion",cerebellar="Cerebellar: to the cerebellum")
tract_list<-cbind(tract_list,tract_names[match(tract_list$code,tract_names$code),-1])
```
### What is drawn
```{r shapes}
# a simpler copy of a surface: its points are gathered into cubes of `size` mm and the points of a
# cube become one, their mean; triangles that shrink to a line or a point go
simplify_mesh<-function(vertices,faces,size) {
cube<-paste(round(vertices[,1]/size),round(vertices[,2]/size),round(vertices[,3]/size))
group<-match(cube,unique(cube))
centres<-rowsum(vertices,group)/as.vector(table(group))
triangles<-matrix(group[faces],ncol=3)
triangles<-triangles[triangles[,1]!=triangles[,2]&triangles[,2]!=triangles[,3]&
triangles[,1]!=triangles[,3],,drop=FALSE]
triangles<-triangles[!duplicated(t(apply(triangles,1,sort))),,drop=FALSE]
result<-list(vertices=centres,faces=triangles-1)
return(result)
}
# the surface of a structure from the cubes of its labels. The cubes are blurred a little (by a bell
# curve of 0.8 mm, one direction at a time), so that the surface is smooth rather than made of
# steps; misc3d's marching cubes trace it where the blurred value is one half; and it is simplified
# into cubes of 2 mm, or 3 mm for the largest structures (over 20 cm³)
smooth_line<-function(v,k) {
n<-length(v)
h<-(length(k)-1)/2
result<-as.vector(stats::filter(c(rep(0,h),v,rep(0,h)),k,sides=2))[(h+1):(h+n)]
return(result)
}
blur<-function(a,sigma) {
k<-dnorm(-3:3,sd=sigma)
k<-k/sum(k)
a<-apply(a,c(2,3),smooth_line,k=k)
a<-aperm(apply(a,c(1,3),smooth_line,k=k),c(2,1,3))
result<-aperm(apply(a,c(1,2),smooth_line,k=k),c(2,3,1))
return(result)
}
structure_labels<-function(x) {
result<-as.integer(unlist(strsplit(c(x$left,x$right,x$middle)," ")))
return(result)
}
label_surface<-function(numbers) {
inside<-array(labels%in%numbers,dim(labels))
found<-which(inside,arr.ind=TRUE)
low<-pmax(apply(found,2,min)-4,1)
high<-pmin(apply(found,2,max)+4,256)
box<-inside[low[1]:high[1],low[2]:high[2],low[3]:high[3]]+0
soup<-misc3d::computeContour3d(blur(box,0.8),maxvol=1,level=0.5,x=low[1]:high[1],
y=low[2]:high[2],z=low[3]:high[3])
# the corners of the triangles, each written once
key<-paste(round(soup[,1],4),round(soup[,2],4),round(soup[,3],4))
corners<-voxel_xyz(soup[!duplicated(key),,drop=FALSE])
triangles<-matrix(match(key,unique(key)),ncol=3,byrow=TRUE)
result<-simplify_mesh(corners,triangles,if(nrow(found)>20000) 3 else 2)
return(result)
}
deep_shapes<-list()
for(k in seq_len(nrow(deep_list)))
deep_shapes[[deep_list$code[k]]]<-label_surface(structure_labels(deep_list[k,]))
ventricle_shapes<-list()
for(k in seq_len(nrow(ventricle_list)))
ventricle_shapes[[ventricle_list$code[k]]]<-label_surface(structure_labels(ventricle_list[k,]))
# a coarse copy of the cortex, drawn as glass around the structures and the tracts. fsaverage5 was
# made by dividing each triangle of an icosahedron into four, five times over, and its first 2,562
# points are those of the fourth time: their triangles are the convex hull of those points on the
# sphere, each turned to face outwards as the lighting needs
coarse<-list()
for(h in names(hemispheres)) {
sphere<-read_surface(h,"sphere")$vertices[1:2562,]
sphere<-sweep(sphere,2,colMeans(sphere))
triangles<-geometry::convhulln(sphere)
a<-sphere[triangles[,2],]-sphere[triangles[,1],]
b<-sphere[triangles[,3],]-sphere[triangles[,1],]
normal<-cbind(a[,2]*b[,3]-a[,3]*b[,2],a[,3]*b[,1]-a[,1]*b[,3],a[,1]*b[,2]-a[,2]*b[,1])
inwards<-rowSums(normal*sphere[triangles[,1],])<0
triangles[inwards,]<-triangles[inwards,c(1,3,2)]
coarse[[h]]<-list(vertices=xyz[points$hemisphere==hemispheres[[h]],][1:2562,],
faces=triangles-1)
}
# the cortex in pieces, one for each region of each hemisphere, so that the pointer can name the
# region: the rows of its points in `points`, and its triangles numbered from 0 within the piece. A
# triangle belongs to the region of its first corner
points$region[points$region=="corpuscallosum"]<-"medialwall"
pieces<-list()
for(h in names(hemispheres)) {
rows<-which(points$hemisphere==hemispheres[[h]])
corner<-points$region[rows][faces[[h]][,1]]
for(r in unique(corner)) {
triangles<-faces[[h]][corner==r,,drop=FALSE]
used<-sort(unique(as.vector(triangles)))
pieces[[length(pieces)+1]]<-list(hemisphere=hemispheres[[h]],region=r,rows=rows[used],
faces=matrix(match(triangles,used)-1,ncol=3))
}
}
```
```{r chart_style}
dark_gray<-"#6b6b6b" # also the color of the notes and the labels
light_gray<-"#d9d9d9" # the medial wall and the corpus callosum
glass_gray<-"#a8a8a8"
# the lobes, the structures under the cortex, the groups of tracts and the ventricles, told apart
# also by color-blind readers (every pair checked)
lobe_colours<-c(frontal="#56B4E9",parietal="#E69F00",temporal="#009E73",occipital="#CC79A7",
cingulate="#D55E00",insula="#F0E442")
deep_colours<-c(cerebellum="#E69F00",brainstem="#4a4a4a",thalamus="#0072B2",caudate="#56B4E9",
putamen="#CC79A7",pallidum="#542788",hippocampus="#F0E442",amygdala="#D55E00",
accumbens="#009E73",ventraldc="#8c564b",callosum=light_gray,chiasm="#1a1a1a")
group_colours<-c(commissural="#0072B2",association="#E69F00",projection="#009E73",
limbic="#CC79A7",cerebellar="#D55E00")
ventricle_colours<-c(lateral="#0072B2",third="#56B4E9",fourth="#009E73",choroid="#D55E00")
# the color scales of the depth under the wrap (pale on the surface, dark deep down) and of the
# thickness, and the four bands of depth of question 2
depth_scale<-list(list(0,"#deebf7"),list(0.25,"#9ecae1"),list(0.5,"#4292c6"),list(0.75,"#2171b5"),
list(1,"#08306b"))
thickness_scale<-list(list(0,"#fde725"),list(0.25,"#5ec962"),list(0.5,"#21918c"),
list(0.75,"#3b528b"),list(1,"#440154"))
band_colours<-c("#c6dbef","#6baed6","#2171b5","#08306b")
# the source of a chart, as a note under it, and the common layout; note_shift moves the note down
# by a number of pixels, which stays the same however tall the plot is
chart<-function(p,title,source,annotations=list(),margin=list(t=70,b=90),note_y=-0.16,
note_shift=0,...) {
note<-list(text=paste("Source:",source),xref="paper",yref="paper",x=0,y=note_y,xanchor="left",
yanchor="top",yshift=note_shift,align="left",showarrow=FALSE,
font=list(size=11,color=dark_gray))
result<-layout(p,
title=list(text=title,x=0.02,xanchor="left",y=0.97,yanchor="top"),
margin=margin,
annotations=c(annotations,list(note)),
...) %>%
config(displaylogo=FALSE)
return(result)
}
legend_top<-list(orientation="h",x=0,y=1.02,yanchor="bottom")
fsaverage<-"FreeSurfer's fsaverage5 and the Desikan-Killiany atlas (ggseg.meshes, ggseg.formats)."
# 3D charts. A mesh of triangles, numbered from 0, in tenths of a mm as whole numbers: plotly for R
# writes any other number with 17 digits, -38.700000000000003 for -38.7. The axes are hidden, and
# the tracts are drawn in tenths of a mm too
add_mesh<-function(p,vertices,faces,name,...) {
result<-add_trace(p,type="mesh3d",x=round(10*vertices[,1]),y=round(10*vertices[,2]),
z=round(10*vertices[,3]),i=faces[,1],j=faces[,2],k=faces[,3],name=name,...)
return(result)
}
# the last step of a 3D chart: build it, drop its second copy of every number ("attrs"), and give
# each trace its color and its text for the pointer, which plotly for R would leave out (the
# color of a mesh, in whose place it puts a color scale) or repeat for every point (the text); NA
# leaves a trace as it is
finish_3d<-function(p,colours,meta) {
result<-plotly_build(p)
result$x$attrs<-NULL
for(k in seq_along(result$x$data)) {
if(!is.na(colours[k])) {
result$x$data[[k]]$color<-colours[[k]]
result$x$data[[k]]$colorscale<-NULL
}
if(!is.na(meta[k])) {
result$x$data[[k]]$meta<-meta[[k]]
result$x$data[[k]]$hovertemplate<-"%{meta}<extra></extra>"
}
}
return(result)
}
# the light, from above, and the scene: no axes, the brain in its true shape, turned by dragging
lighting<-list(ambient=0.45,diffuse=0.75,specular=0.15,roughness=0.6,fresnel=0.1)
glass_lighting<-list(ambient=0.9,diffuse=0.2,specular=0,roughness=1,fresnel=0.2)
above<-list(x=0,y=0,z=1e5)
scene<-function(eye=list(x=-1.35,y=0.25,z=0.3),domain=list(x=c(0,1),y=c(0,1))) {
axis<-list(visible=FALSE)
result<-list(xaxis=axis,yaxis=axis,zaxis=axis,aspectmode="data",dragmode="turntable",
camera=list(eye=eye),domain=domain)
return(result)
}
# buttons under a 3D chart that turn the brain to one of six views
views<-list(Left=c(-1.5,0,0.1),Right=c(1.5,0,0.1),Front=c(0,1.5,0.1),Back=c(0,-1.5,0.1),
Top=c(0,0,1.6),Below=c(0,0,-1.6))
view_buttons<-list()
for(v in names(views)) {
up<-if(v%in%c("Top","Below")) list(x=0,y=1,z=0) else list(x=0,y=0,z=1)
eye<-list(x=views[[v]][1],y=views[[v]][2],z=views[[v]][3])
camera<-list(eye=eye,up=up,center=list(x=0,y=0,z=0))
view_buttons[[v]]<-list(label=v,method="relayout",args=list(list(scene.camera=camera)))
}
view_menu<-list(type="buttons",direction="right",x=0,y=0,xanchor="left",yanchor="top",
showactive=FALSE,buttons=unname(view_buttons))
# a volume in cm³, to a tenth, or to a hundredth below 0.1 cm³ (the optic chiasm)
volume_text<-function(x) {
result<-if(x<0.1) format(round(x,2),nsmall=2) else one(x)
return(result)
}
# the volume of a structure: on each side, or in all for one in the middle
volume_words<-function(x) {
result<-if(x$left_volume>0) paste0(volume_text(x$left_volume)," cm³ on the left, ",
volume_text(x$right_volume)," on the right") else
paste0(volume_text(x$volume)," cm³")
return(result)
}
# the text for the pointer: a name in bold, and lines under it
pointer_text<-function(name,...) {
result<-paste0("<b>",name,"</b><br>",paste(...,sep="<br>"))
return(result)
}
```
---
## 1. What are the parts of the cortex?
```{r parts_numbers}
lobe_both<-lobe_both[order(-lobe_both$area),]
total_area<-sum(cortex$area)/100
side_area<-tapply(cortex$area,cortex$hemisphere,sum)/100
largest<-region_both[which.max(region_both$area),]
smallest<-region_both[which.min(region_both$area),]
share<-setNames(lobe_both$share,lobe_both$key)
```
**`r upper_first(count_words(nrow(lobes)))` lobes and `r nrow(region_both)` regions in each hemisphere.** Spread out flat, the cortex of the average brain would cover **`r number(total_area)` cm²**, a square of `r number(sqrt(total_area))` cm on each side (measured halfway through its thickness); the left hemisphere has `r one(abs(100*(side_area[["left"]]/side_area[["right"]]-1)))`% `r if(side_area[["left"]]>side_area[["right"]]) "more" else "less"` of it than the right. The **frontal lobe** has `r percent(share[["frontal"]])` of it, the **parietal lobe** `r percent(share[["parietal"]])`, the **temporal lobe** `r percent(share[["temporal"]])` and the **occipital lobe** `r percent(share[["occipital"]])`; the **cingulate gyrus**, on the inner side of each hemisphere, and the **insula**, hidden under the frontal and temporal lobes, share the rest. Of the regions, the `r lower_first(largest$name)` is the largest, `r number(largest$area)` cm² in the two hemispheres together, and the `r lower_first(smallest$name)` the smallest, `r number(smallest$area)` cm².
```{r parts, fig.height = 7}
#| fig-alt: "3D model of the cortex of the average human brain, seen from the left and coloured by lobe: the frontal lobe at the front, the parietal lobe at the top behind it, the temporal lobe at the side below them, the occipital lobe at the back"
p<-plot_ly()
lobe_trace<-c()
region_trace<-c()
meta<-c()
for(piece in pieces) {
region<-regions[regions$code==piece$region,]
lobe<-region_both$lobe[region_both$key==piece$region]
name<-paste0(region$name,", ",piece$hemisphere)
p<-add_mesh(p,xyz[piece$rows,],piece$faces,name,flatshading=FALSE,lighting=lighting,
lightposition=above,showlegend=FALSE)
if(piece$region=="medialwall") {
lobe_trace<-c(lobe_trace,light_gray)
region_trace<-c(region_trace,light_gray)
meta<-c(meta,pointer_text(name,region$role))
} else {
side<-region_side[region_side$key==paste(piece$hemisphere,piece$region),]
lobe_trace<-c(lobe_trace,lobe_colours[[lobe]])
region_trace<-c(region_trace,atlas$palette[[paste0(substr(piece$hemisphere,1,1),"h_",
piece$region)]])
meta<-c(meta,pointer_text(name,lobes$name[lobes$code==lobe],region$role,
paste0(number(side$area)," cm² of cortex, ",one(side$thickness),
" mm thick on average")))
}
}
colour_menu<-list(type="buttons",direction="right",x=0,y=1,xanchor="left",yanchor="bottom",
buttons=list(list(label="Lobes",method="restyle",
args=list(list(color=as.list(lobe_trace)))),
list(label="Regions",method="restyle",
args=list(list(color=as.list(region_trace))))))
p %>%
chart("The cortex of the average brain, by lobe",
paste(fsaverage,"Drag to turn, scroll to zoom."),
margin=list(t=100,b=80,l=0,r=0),note_y=0,note_shift=-40,scene=scene(),
updatemenus=list(colour_menu,view_menu)) %>%
finish_3d(lobe_trace,meta)
```
The colors of the lobes follow the atlas, which counts the cingulate gyrus as a lobe of its own. The button **Regions** colors the `r nrow(region_both)` regions instead, and the pointer over a region gives its name, its lobe, what it does and its size. Each region does more than its one line says, and most of what we do takes many regions at once.
```{r areas, fig.height = 6}
#| fig-alt: "Treemap of the area of the cortex: a box for each lobe, as large as its area, and in it a box for each of its regions; the frontal lobe has the largest box, and the superior frontal gyrus is its largest region"
children<-data.frame(id=region_both$key,parent=region_both$lobe,label=region_both$name,
area=round(region_both$area,1),colour=lobe_colours[region_both$lobe])
# the insula is both a lobe and a region
children$id[children$id=="insula"]<-"insula region"
# a lobe's box holds exactly its regions' boxes
parents<-data.frame(id=lobe_both$key,parent="",label=lobe_both$name,
area=as.vector(tapply(children$area,children$parent,sum)[lobe_both$key]),
colour=lobe_colours[lobe_both$key])
p<-plot_ly(rbind(parents,children),type="treemap",ids=~id,parents=~parent,labels=~label,
values=~area,branchvalues="total",
marker=list(colors=~colour,line=list(color="white",width=1)),
texttemplate="%{label}<br>%{value:.0f} cm²",
hovertemplate=paste0("%{label}: %{value:.0f} cm², %{percentRoot:.1%} of the cortex",
"<extra></extra>"))
chart(p,"The area of each lobe and region, both hemispheres, cm²",
paste("FreeSurfer's fsaverage5, measured halfway through the cortex,",
"and the Desikan-Killiany atlas."),
uniformtext=list(minsize=10,mode="hide"),margin=list(t=50,b=50,l=0,r=0),note_y=0)
```
Each box is as large as the area of its lobe or region; a click on a lobe opens its box.
---
## 2. How much of the cortex is hidden in the folds?
```{r folds_numbers}
deep_share<-100*sum(cortex$area[cortex$depth>5])/sum(cortex$area)
surface_share<-100*sum(cortex$area[cortex$depth<=2])/sum(cortex$area)
# the depth that half of the area of the cortex lies deeper than
by_depth<-order(cortex$depth)
half_depth<-cortex$depth[by_depth][which(cumsum(cortex$area[by_depth])>=sum(cortex$area)/2)[1]]
folded<-pial_area/wrap_area
deepest<-region_both[which.max(region_both$depth),]
shallowest<-region_both[which.min(region_both$depth),]
most_folded<-lobe_both[which.max(lobe_both$deep),]
least_folded<-lobe_both[which.min(lobe_both$deep),]
```
**`r if(deep_share>50) "Most of it." else "Much of it."`** The outer surface of the cortex has `r one(folded)` times the area of the wraps around the two hemispheres: `r number(pial_area/100)` cm² against `r number(wrap_area/100)`. Only `r percent(surface_share)` of the cortex lies within 2 mm of the wrap; `r percent(deep_share)` lies more than 5 mm under it, and half of it more than `r number(half_depth)` mm under it. Deepest of all is the `r lower_first(deepest$name)`, `r number(deepest$depth)` mm under the wrap on average, and the least deep the `r lower_first(shallowest$name)`, `r one(shallowest$depth)` mm.
```{r inflated, fig.height = 7}
#| fig-alt: "3D model of the cortex of the average brain blown up like a balloon, so that its folds open out, seen from the left and the front: the colour shows how deep each point lies under the wrap in the folded brain, pale on the ridges and dark blue in the grooves and on the insula"
# the depth in whole mm; the thickness in tenths of a mm, the labels of its color bar in mm
depth_max<-5*ceiling(quantile(cortex$depth,0.95)/5)
thickness_range<-round(2*quantile(cortex$thickness,c(0.02,0.98)))/2
thickness_ticks<-seq(10*thickness_range[[1]],10*thickness_range[[2]],by=5)
p<-plot_ly()
colours<-c()
meta<-c()
coloured<-c()
depth_values<-list()
thickness_values<-list()
for(k in seq_along(pieces)) {
piece<-pieces[[k]]
region<-regions[regions$code==piece$region,]
name<-paste0(region$name,", ",piece$hemisphere)
inflated<-as.matrix(points[piece$rows,c("inflated_x","inflated_y","inflated_z")])
if(piece$region=="medialwall") {
p<-add_mesh(p,inflated,piece$faces,name,flatshading=FALSE,lighting=lighting,
lightposition=above,showlegend=FALSE)
colours<-c(colours,light_gray)
meta<-c(meta,pointer_text(name,region$role))
} else {
depth<-round(points$depth[piece$rows])
p<-add_mesh(p,inflated,piece$faces,name,intensity=depth,colorscale=depth_scale,cmin=0,
cmax=depth_max,showscale=length(coloured)==0,flatshading=FALSE,
colorbar=list(title=list(text="mm under<br>the wrap"),len=0.5,thickness=12),
lighting=lighting,lightposition=above,showlegend=FALSE)
side<-region_side[region_side$key==paste(piece$hemisphere,piece$region),]
colours<-c(colours,NA)
meta<-c(meta,pointer_text(name,paste0(number(side$depth)," mm under the wrap on average, ",
percent(side$deep)," of it more than 5 mm"),
paste0(one(side$thickness)," mm thick on average")))
coloured<-c(coloured,k)
depth_values[[length(depth_values)+1]]<-depth
thickness_values[[length(thickness_values)+1]]<-round(10*points$thickness[piece$rows])
}
}
depth_button<-list(label="Depth",method="restyle",
args=list(list(intensity=depth_values,colorscale=list(depth_scale),cmin=0,
cmax=depth_max,colorbar.title.text="mm under<br>the wrap",
colorbar.tickmode="auto"),
coloured-1))
thickness_button<-list(label="Thickness",method="restyle",
args=list(list(intensity=thickness_values,colorscale=list(thickness_scale),
cmin=min(thickness_ticks),cmax=max(thickness_ticks),
colorbar.title.text="mm thick",colorbar.tickmode="array",
colorbar.tickvals=list(thickness_ticks),
colorbar.ticktext=list(one(thickness_ticks/10))),
coloured-1))
measure_menu<-list(type="buttons",direction="right",x=0,y=1,xanchor="left",yanchor="bottom",
buttons=list(depth_button,thickness_button))
p %>%
chart("The cortex blown up: how deep each point lies in the folded brain",
paste(fsaverage,"Grey: the medial wall."),
margin=list(t=100,b=80,l=0,r=0),note_y=0,note_shift=-40,scene=scene(),
updatemenus=list(measure_menu,view_menu)) %>%
finish_3d(colours,meta)
```
This is the same cortex as in the first chart, blown up like a balloon until its folds open out, as FreeSurfer does to show all of it at once; each point keeps the color of its depth in the folded brain. The dark patches are the floors of the grooves, and the large dark field on the side is the insula, which the frontal and temporal lobes fold over. The button **Thickness** colors the cortex by its thickness instead, the subject of question 3.
```{r bands, fig.height = 4.5}
#| fig-alt: "Stacked bar chart of the area of each lobe by its depth under the wrap: within 2 mm, 2 to 10 mm, 10 to 20 mm and more than 20 mm; the insula lies almost all more than 20 mm deep, while the cingulate gyrus and the occipital lobe have the most area near the surface"
bands<-cut(cortex$depth,c(0,2,10,20,Inf),c("Within 2 mm","2 to 10 mm","10 to 20 mm","Over 20 mm"),
right=FALSE)
band_area<-rbind(tapply(cortex$area,list(cortex$lobe,bands),sum),all=tapply(cortex$area,bands,sum))
band_area[is.na(band_area)]<-0
band_share<-100*prop.table(band_area,1)
band_share<-band_share[order(band_share[,"Over 20 mm"]+band_share[,"10 to 20 mm"]),]
lobe_label<-ifelse(rownames(band_share)=="all","<b>Whole cortex</b>",
lobes$name[match(rownames(band_share),lobes$code)])
p<-plot_ly()
for(b in colnames(band_share))
p<-add_bars(p,y=lobe_label,x=round(band_share[,b],1),name=b,orientation="h",
marker=list(color=band_colours[match(b,colnames(band_share))]),
hovertemplate=paste0("%{y}: %{x:.0f}% ",lower_first(b),"<extra></extra>"))
chart(p,"How deep each lobe lies under the wrap, % of its area",
paste("FreeSurfer's fsaverage5 and the Desikan-Killiany atlas.",
"The wrap: the convex hull of each hemisphere."),
barmode="stack",legend=c(legend_top,list(traceorder="normal")),margin=list(t=90,b=90),
note_y=-0.2,xaxis=list(title="",ticksuffix="%",range=c(0,100)),
yaxis=list(title="",categoryorder="array",categoryarray=lobe_label,automargin=TRUE))
```
The lobes are not folded away alike: `r percent(most_folded$deep)` of the `r lower_first(most_folded$name)` lies more than 5 mm under the wrap, and `r percent(least_folded$deep)` of the `r lower_first(least_folded$name)`. The wrap reaches into no groove, so even the ridges of the cortex lie under it where a hemisphere curves inwards, as on its underside, between the temporal lobe and the frontal lobe.
---
## 3. Where is the cortex thickest?
```{r thickness_numbers}
mean_thickness<-weighted.mean(cortex$thickness,cortex$area)
by_thickness<-region_both[order(region_both$thickness),]
thinnest<-by_thickness[1,]
thickest<-by_thickness[nrow(by_thickness),]
thin_four<-by_thickness$key[1:4]
thick_four<-rev(by_thickness$key)[1:4]
# the regions of seeing and touch at the back of the brain, and those of memory and emotion at its
# front and bottom
senses<-c("pericalcarine","cuneus","lingual","lateraloccipital","postcentral","superiorparietal")
feelings<-c("temporalpole","entorhinal","parahippocampal","insula","rostralanteriorcingulate",
"caudalanteriorcingulate","medialorbitofrontal","frontalpole")
motor<-region_both[region_both$key=="precentral",]
touch<-region_both[region_both$key=="postcentral",]
left<-region_side[grepl("^left",region_side$key),]
right<-region_side[grepl("^right",region_side$key),]
region_both$left<-left$thickness[match(paste("left",region_both$key),left$key)]
region_both$right<-right$thickness[match(paste("right",region_both$key),right$key)]
side_gap<-max(abs(region_both$left-region_both$right))
```
**Between `r one(thinnest$thickness)` and `r one(thickest$thickness)` mm, `r one(mean_thickness)` on average.** The four thinnest regions are `r and_list(paste("the",lower_first(regions$name[match(thin_four,regions$code)])))`, `r if(all(thin_four%in%senses)) "where sight and touch arrive, at the back of the brain" else "at the end of the chart below"`. The four thickest are `r and_list(paste("the",lower_first(regions$name[match(thick_four,regions$code)])))`, `r if(all(thick_four%in%feelings)) "at the front and at the bottom of the brain, where memory and emotion are handled" else "at the top of the chart below"`. `r if(motor$thickness-touch$thickness>0.2) paste0("The two strips on either side of the central sulcus differ too: the ",lower_first(motor$name),", which moves the body, is ",one(motor$thickness)," mm thick, and the ",lower_first(touch$name)," behind it, which feels it, ",one(touch$thickness)," mm.") else ""` The two hemispheres hardly differ: a region is at most `r one(side_gap)` mm thicker on one side than on the other.
```{r thickness, fig.height = 8.5}
#| fig-alt: "Bar chart of the mean thickness of each of the 34 regions of the cortex, sorted and coloured by lobe: thinnest the pericalcarine cortex, the cuneus and the postcentral gyrus, thickest the temporal pole, the entorhinal cortex and the insula"
p<-plot_ly()
for(l in lobes$code) {
x<-region_both[region_both$lobe==l,]
p<-add_bars(p,data=x,y=~name,x=~round(thickness,2),name=lobes$name[lobes$code==l],
orientation="h",marker=list(color=lobe_colours[[l]]),
customdata=~paste0("left ",one(left),", right ",one(right)))
}
p<-style(p,hovertemplate="%{y}: %{x:.1f} mm (%{customdata})<extra></extra>")
chart(p,"The mean thickness of each region of the cortex, mm",
"fsaverage5 and the Desikan-Killiany atlas: the distance from the pial to the white surface.",
legend=legend_top,margin=list(t=100,b=70,l=10),note_y=-0.07,
xaxis=list(title="",ticksuffix=" mm"),
yaxis=list(title="",categoryorder="array",categoryarray=by_thickness$name,automargin=TRUE))
```
The thickness here is the distance from each point of the outer surface of the cortex to the same point of its inner surface, close to the way FreeSurfer measures it ([Fischl and Dale 2000](https://doi.org/10.1073/pnas.200033797)). The button **Thickness** of the chart of question 2 shows it over the whole cortex.
---
## 4. What lies under the cortex?
```{r deep_numbers}
cerebellum<-deep_list[deep_list$code=="cerebellum",]
cerebellum_share<-100*cerebellum$volume/brain_volume
largest<-deep_list[which.max(deep_list$volume),]
middle_kinds<-c("thalamus","caudate","putamen","pallidum","hippocampus","amygdala","accumbens")
middle_structures<-deep_list[deep_list$code%in%middle_kinds,]
largest_middle<-middle_structures[which.max(middle_structures$volume),]
hippocampus<-deep_list[deep_list$code=="hippocampus",]
amygdala<-deep_list[deep_list$code=="amygdala",]
```
**`r upper_first(count_words(nrow(deep_list)))` structures, and the largest by far is the `r lower_first(largest$name)`.** The cerebellum takes up `r number(cerebellum$volume)` cm³, `r percent(cerebellum_share)` of the brain, which fills `r number(brain_volume)` cm³ without its spaces filled with fluid. Small as it is, it holds most of the brain's nerve cells: about 69 of 86 billion, while the cerebral cortex and its white matter, 82% of the brain's weight, hold only 19% of them ([Azevedo et al. 2009](https://doi.org/10.1002/cne.21974)). Of the structures in the middle of the brain, the `r lower_first(largest_middle$name)` is the largest, `r one(largest_middle$left_volume)` cm³ on the left and `r one(largest_middle$right_volume)` on the right; the **hippocampus**, where new memories are made, takes up `r one((hippocampus$left_volume+hippocampus$right_volume)/2)` cm³ on each side, and the **amygdala**, of fear and emotion, `r one((amygdala$left_volume+amygdala$right_volume)/2)`.
```{r deep_chart, fig.height = 7.5}
#| fig-alt: "3D model of the structures under the cortex inside a glass cortex, seen from the left and the front: the cerebellum and the brain stem at the bottom and the back, the thalamus, the basal ganglia, the hippocampus and the amygdala in the middle, and the corpus callosum arching above them"
p<-plot_ly()
for(h in names(hemispheres))
p<-add_mesh(p,coarse[[h]]$vertices,coarse[[h]]$faces,"Cortex",opacity=0.1,hoverinfo="skip",
lighting=glass_lighting,showlegend=FALSE)
colours<-c(glass_gray,glass_gray)
meta<-c(NA,NA)
for(k in seq_len(nrow(deep_list))) {
structure<-deep_list[k,]
shape<-deep_shapes[[structure$code]]
p<-add_mesh(p,shape$vertices,shape$faces,structure$name,flatshading=FALSE,lighting=lighting,
lightposition=above,showlegend=TRUE)
colours<-c(colours,deep_colours[[structure$code]])
meta<-c(meta,pointer_text(structure$name,structure$role,volume_words(structure)))
}
p %>%
chart("The structures under the cortex",
paste("FreeSurfer's segmentation of fsaverage (aseg.mgz), from fsbrain's test data.",
"A click on a name hides it."),
margin=list(t=60,b=80,l=0,r=0),note_y=0,note_shift=-40,
scene=scene(list(x=-1.25,y=0.75,z=0.3),list(x=c(0,0.8),y=c(0,1))),
legend=list(x=1,xanchor="right",y=0.95,itemsizing="constant"),
updatemenus=list(view_menu)) %>%
finish_3d(colours,meta)
```
The glass is a coarse copy of the cortex. The structures are traced from FreeSurfer's labeled cubes of 1 mm and smoothed a little. Between them lie the ventricles, the subject of the next question.
---
## 5. What fills the hollows inside the brain?
```{r ventricle_numbers}
spaces<-ventricle_list[ventricle_list$code!="choroid",]
fluid_volume<-sum(spaces$volume)
lateral<-ventricle_list[ventricle_list$code=="lateral",]
third<-ventricle_list[ventricle_list$code=="third",]
fourth<-ventricle_list[ventricle_list$code=="fourth",]
```
**Fluid: `r one(fluid_volume)` cm³ of it, in four ventricles.** The brain is hollow in the middle. Its two **lateral ventricles**, one in each hemisphere, arch from the front of the brain back over the thalamus and then down into the temporal lobe; they hold `r one(lateral$left_volume)` cm³ on the left and `r one(lateral$right_volume)` on the right. Both open into the narrow **third ventricle**, between the two halves of the thalamus (`r one(third$volume)` cm³), which drains through a thin channel, the aqueduct, into the **fourth ventricle**, between the brain stem and the cerebellum (`r one(fourth$volume)` cm³); from there the fluid flows out around the brain and the spinal cord. Most of it is made by the **choroid plexus**, a fringe of small blood vessels in the ventricles, and it is renewed about four times a day. A living adult has about 150 ml of it, 25 ml of which is in the ventricles ([Sakka et al. 2011](https://doi.org/10.1016/j.anorl.2011.03.002)); the ventricles of the average brain hold `r if(fluid_volume>25) "more" else "less"`, and like all its sizes theirs are not those of any one head.
```{r ventricles, fig.height = 7.5}
#| fig-alt: "3D model of the ventricles inside a glass cortex, seen from the left and the front: the two lateral ventricles arching from the front of the brain to the back and down into the temporal lobes, the narrow third ventricle in the middle below them, the fourth ventricle further back and lower, in front of the cerebellum, and the choroid plexus inside the lateral ventricles"
p<-plot_ly()
for(h in names(hemispheres))
p<-add_mesh(p,coarse[[h]]$vertices,coarse[[h]]$faces,"Cortex",opacity=0.1,hoverinfo="skip",
lighting=glass_lighting,showlegend=FALSE)
colours<-c(glass_gray,glass_gray)
meta<-c(NA,NA)
for(k in seq_len(nrow(ventricle_list))) {
space<-ventricle_list[k,]
shape<-ventricle_shapes[[space$code]]
p<-add_mesh(p,shape$vertices,shape$faces,space$name,flatshading=FALSE,lighting=lighting,
lightposition=above,showlegend=TRUE)
colours<-c(colours,ventricle_colours[[space$code]])
meta<-c(meta,pointer_text(space$name,space$role,volume_words(space)))
}
p %>%
chart("The ventricles, the hollows of the brain",
paste("FreeSurfer's segmentation of fsaverage (aseg.mgz), from fsbrain's test data.",
"A click on a name hides it."),
margin=list(t=60,b=80,l=0,r=0),note_y=0,note_shift=-40,
scene=scene(list(x=-1.25,y=0.75,z=0.3),list(x=c(0,0.8),y=c(0,1))),
legend=list(x=1,xanchor="right",y=0.95,itemsizing="constant"),
updatemenus=list(view_menu)) %>%
finish_3d(colours,meta)
```
FreeSurfer's segmentation does not label the aqueduct, so the third and the fourth ventricle look apart here.
---
## 6. How are the parts wired together?
```{r tract_numbers}
longest<-tract_list[which.max(tract_list$length),]
shortest<-tract_list[which.min(tract_list$length),]
arcuate<-tract_list[tract_list$code=="af"&tract_list$side=="left",]
group_count<-table(factor(tract_list$group,levels=names(groups)))
cerebellar<-if(group_count[["cerebellar"]]==1) "one carries signals into the cerebellum" else
paste(group_count[["cerebellar"]],"carry signals into the cerebellum")
```
**`r nrow(tract_list)` bundles in this atlas, from `r number(shortest$length/10)` to `r number(longest$length/10)` cm long.** Of them, `r group_count[["commissural"]]` cross from one hemisphere to the other (the eight parts of the corpus callosum and the anterior commissure), `r group_count[["association"]]` link areas within a hemisphere, `r group_count[["projection"]]` run between the cortex and the thalamus or the spinal cord, `r group_count[["limbic"]]` belong to the circuits of memory and emotion, and `r cerebellar`. The **arcuate fasciculus**, which joins the speech areas at the front and at the back of the brain, is `r number(arcuate$length)` mm long on the left. The longest of all is the **`r lower_first(longest$name)`**, `r number(longest$length)` mm`r if(longest$code=="cst") ", from the motor cortex down to the bottom of the brain stem, where the atlas ends and the tract goes on down the spinal cord" else ""`; the shortest the `r lower_first(shortest$name)`, `r number(shortest$length)` mm.
```{r tract_chart, fig.height = 7.5}
#| fig-alt: "3D model of 42 tracts of white matter inside a glass cortex, seen from the left and the front, as lines coloured by kind: the corpus callosum arching across the middle, long association tracts running from the front to the back, and the corticospinal tracts running down into the brain stem"
p<-plot_ly()
for(h in names(hemispheres))
p<-add_mesh(p,coarse[[h]]$vertices,coarse[[h]]$faces,"Cortex",opacity=0.08,hoverinfo="skip",
lighting=glass_lighting,showlegend=FALSE)
colours<-c(glass_gray,glass_gray)
meta<-c(NA,NA)
shown<-c()
for(k in order(match(tract_list$group,names(groups)),tract_list$code)) {
tract<-tract_list[k,]
line<-as.data.frame(round(10*tract_points[[k]]))
p<-add_trace(p,data=line,x=~V1,y=~V2,z=~V3,type="scatter3d",mode="lines",
name=groups[[tract$group]],legendgroup=tract$group,
showlegend=!tract$group%in%shown,
line=list(color=group_colours[[tract$group]],width=6))
shown<-c(shown,tract$group)
side<-if(tract$side=="middle") "" else paste0(", ",tract$side)
colours<-c(colours,NA)
meta<-c(meta,pointer_text(paste0(tract$name,side),tract$role,
paste0(number(tract$length)," mm long")))
}
p %>%
chart("The tracts of white matter, by kind",
"TRACULA's atlas of white-matter tracts, from ggseg.formats. A click on a kind hides it.",
margin=list(t=120,b=80,l=0,r=0),note_y=0,note_shift=-40,
scene=scene(list(x=-1.25,y=0.75,z=0.3)),legend=c(legend_top,list(itemsizing="constant")),
updatemenus=list(view_menu)) %>%
finish_3d(colours,meta)
```
Each line is the middle of a bundle of fibers several millimeters thick, which fans out where it reaches the cortex. The pointer over a line names the tract, says what it carries and how long it is.
---
## So, what does it mean?
**The brain is a large sheet packed into a small skull, hollow in the middle and wired across.**
1. **A folded sheet**: `r number(total_area)` cm² of cortex, whose outer surface has `r one(folded)` times the area of the wraps around the hemispheres; `r percent(deep_share)` of it lies more than 5 mm deep in the folds.
2. **Thin and thick**: from `r one(thinnest$thickness)` mm in the `r lower_first(thinnest$name)`, where the signals of the eyes arrive, to `r one(thickest$thickness)` mm in the `r lower_first(thickest$name)`.
3. **Small parts with large tasks**: the hippocampus, `r one((hippocampus$left_volume+hippocampus$right_volume)/2)` cm³ on each side, makes new memories; the cerebellum, `r percent(cerebellum_share)` of the brain, holds most of its nerve cells.
4. **Hollow in the middle**: `r one(fluid_volume)` cm³ of fluid in four ventricles, made by the choroid plexus and renewed about four times a day.
5. **Wired along and across**: `r nrow(tract_list)` bundles link the lobes within each hemisphere, the two hemispheres with each other, and the cortex with the structures under it and the spinal cord.
**What this does not show.** The brain is an average of many brains, and smoother than any one of them: averaging blurs the folds, so a real brain has more area and deeper folds than this one, and its parts differ in size and shape from person to person. The regions of the atlas follow the folds, not what the cortex does, and their roles are simplified: each region does more than one thing, and most tasks use many regions. The thickness and the depth are measured on the average surfaces, not averaged over people. The structures under the cortex and the ventricles are traced from FreeSurfer's labeled cubes of 1 mm and smoothed a little; the tracts come from an atlas with a frame of its own, are laid on the volume as shown under *The data*, and are the middle lines of their bundles. The volumes are those of the average brain, whose size is set by the template it was laid on, not by any one head.
For how the brain can be fooled by what the eyes see, see [Illusions in R](ILLUSTRATION_ILLUSIONS.html).
---
## Sources
- Azevedo, F.A.C. and others (2009), [Equal numbers of neuronal and nonneuronal cells make the human brain an isometrically scaled-up primate brain](https://doi.org/10.1002/cne.21974), *Journal of Comparative Neurology* 513, 532–541.
- Betts, J.G. and others (2022), [Anatomy and Physiology 2e](https://openstax.org/books/anatomy-and-physiology-2e/pages/13-2-the-central-nervous-system), chapter 13, The Anatomy of the Nervous System, OpenStax: the lobes, the structures under the cortex, the ventricles and what they do.
- Catani, M. and Thiebaut de Schotten, M. (2008), [A diffusion tensor imaging tractography atlas for virtual in vivo dissections](https://doi.org/10.1016/j.cortex.2008.05.004), *Cortex* 44, 1105–1132: the tracts and what they link.
- Desikan, R.S. and others (2006), [An automated labeling system for subdividing the human cerebral cortex on MRI scans into gyral based regions of interest](https://doi.org/10.1016/j.neuroimage.2006.01.021), *NeuroImage* 31, 968–980.
- Dick, A.S., Garic, D., Graziano, P. and Tremblay, P. (2019), [The frontal aslant tract (FAT) and its role in speech, language and executive function](https://doi.org/10.1016/j.cortex.2018.10.015), *Cortex* 111, 148–163.
- Epstein, R. and Kanwisher, N. (1998), [A cortical representation of the local visual environment](https://doi.org/10.1038/33402), *Nature* 392, 598–601: the parahippocampal gyrus and places.
- Feng, D. and Tierney, L. (2008), [Computing and displaying isosurfaces in R](https://doi.org/10.18637/jss.v028.i01), *Journal of Statistical Software* 28(1): misc3d, which traces the surfaces of the structures and the ventricles.
- Fischl, B. and Dale, A.M. (2000), [Measuring the thickness of the human cerebral cortex from magnetic resonance images](https://doi.org/10.1073/pnas.200033797), *Proceedings of the National Academy of Sciences* 97, 11050–11055.
- Fischl, B., Sereno, M.I., Tootell, R.B.H. and Dale, A.M. (1999), [High-resolution intersubject averaging and a coordinate system for the cortical surface](https://doi.org/10.1002/(SICI)1097-0193(1999)8%3A4%3C272%3A%3AAID-HBM10%3E3.0.CO%3B2-4), *Human Brain Mapping* 8, 272–284: fsaverage.
- Fischl, B. and others (2002), [Whole brain segmentation: automated labeling of neuroanatomical structures in the human brain](https://doi.org/10.1016/S0896-6273(02)00569-X), *Neuron* 33, 341–355: the segmentation of the structures under the cortex and of the ventricles.
- Kanwisher, N., McDermott, J. and Chun, M.M. (1997), [The fusiform face area: a module in human extrastriate cortex specialized for face perception](https://doi.org/10.1523/JNEUROSCI.17-11-04302.1997), *Journal of Neuroscience* 17, 4302–4311.
- Maffei, C. and others (2021), [Using diffusion MRI data acquired with ultra-high gradient strength to improve tractography in routine-quality data](https://doi.org/10.1016/j.neuroimage.2021.118706), *NeuroImage* 245, 118706: the 42 tracts of TRACULA.
- Mowinckel, A.M. and Vidal-Piñeiro, D. (2020), [Visualization of brain statistics with R packages ggseg and ggseg3d](https://doi.org/10.1177/2515245920928009), *Advances in Methods and Practices in Psychological Science* 3, 466–483; the surfaces and the atlases come from the packages [ggseg.formats](https://ggsegverse.github.io/ggseg.formats/) and [ggseg.meshes](https://ggsegverse.github.io/ggseg.meshes/).
- Plotly, [MRI Reconstruction](https://brain-viewer.plotly.app/), a sample app of Dash ([code on GitHub](https://github.com/plotly/dash-sample-apps/tree/master/apps/dash-brain-viewer)).
- Sakka, L., Coll, G. and Chazal, J. (2011), [Anatomy and physiology of cerebrospinal fluid](https://doi.org/10.1016/j.anorl.2011.03.002), *European Annals of Otorhinolaryngology, Head and Neck Diseases* 128, 309–316.
- Schäfer, T. and Ecker, C. (2020), [fsbrain: an R package for the visualization of structural neuroimaging data](https://doi.org/10.1101/2020.09.18.302935), *bioRxiv*: its server keeps the copy of FreeSurfer's segmentation of fsaverage that the page downloads.
- Yendiki, A. and others (2011), [Automated probabilistic reconstruction of white-matter pathways in health and disease using an atlas of the underlying anatomy](https://doi.org/10.3389/fninf.2011.00023), *Frontiers in Neuroinformatics* 5, 23: TRACULA.
---
## Acknowledgments
The average brain, the atlas of its regions, its segmentation and the atlas of its tracts come from [FreeSurfer](https://surfer.nmr.mgh.harvard.edu/). The surfaces drawn on this page are modified from FreeSurfer's: they are turned and moved into one frame, cut into regions, simplified and, for the structures under the cortex and the ventricles, traced from the labeled volume; they are not FreeSurfer's original files. The surfaces of the cortex and the atlases come from the R packages ggseg.formats and ggseg.meshes, © 2026 their authors, under the MIT license, and the copy of the segmentation from the server of the fsbrain package. The idea of a brain that turns under the mouse comes from Plotly's [MRI Reconstruction](https://brain-viewer.plotly.app/) app.
All or portions of this licensed product (such portions are the "Software") have been obtained under license from The General Hospital Corporation "MGH" and are subject to the following terms and conditions:
<details>
<summary>The FreeSurfer Software License Agreement, version 1.0 (February 2011), part B</summary>
```text
PART B. DOWNLOADING AGREEMENT - License from MGH with Right to Sublicense
("Software License").
1. As used in this Software License, "you" means the individual
downloading and/or using, reproducing, modifying, displaying and/or
distributing the Software and the institution or entity which
employs or is otherwise affiliated with such individual in
connection therewith. The General Hospital Corporation ("MGH")
hereby grants you, with right to sublicense, with
respect to MGH's rights in the software, and data, if any,
which is the subject of this Software License (collectively, the
"Software"), a royalty-free, non-exclusive license to use,
reproduce, make derivative works of, display and distribute the
Software, provided that:
(a) you accept and adhere to all of the terms and conditions of this
Software License;
(b) in connection with any copy of or sublicense of all or any portion
of the Software, all of the terms and conditions in this Software
License shall appear in and shall apply to such copy and such
sublicense, including without limitation all source and executable
forms and on any user documentation, prefaced with the following
words: "All or portions of this licensed product (such portions are
the "Software") have been obtained under license from The General Hospital
Corporation "MGH" and are subject to the following terms and
conditions:"
(c) you preserve and maintain all applicable attributions, copyright
notices and licenses included in or applicable to the Software;
(d) modified versions of the Software must be clearly identified and
marked as such, and must not be misrepresented as being the original
Software; and
(e) you consider making, but are under no obligation to make, the
source code of any of your modifications to the Software freely
available to others on an open source basis.
2. The license granted in this Software License includes without
limitation the right to (i) incorporate the Software into
proprietary programs (subject to any restrictions applicable to
such programs), (ii) add your own copyright statement to your
modifications of the Software, and (iii) provide additional or
different license terms and conditions in your sublicenses of
modifications of the Software; provided that in each case your use,
reproduction or distribution of such modifications otherwise
complies with the conditions stated in this Software License.
3. This Software License does not grant any rights with respect to
third party software, except those rights that MGH has been
authorized by a third party to grant to you, and accordingly you
are solely responsible for (i) obtaining any permissions from third
parties that you need to use, reproduce, make derivative works of,
display and distribute the Software, and (ii) informing your
sublicensees, including without limitation your end-users, of their
obligations to secure any such required permissions.
4. The Software has been designed for research purposes only and has
not been reviewed or approved by the Food and Drug Administration
or by any other agency. YOU ACKNOWLEDGE AND AGREE THAT CLINICAL
APPLICATIONS ARE NEITHER RECOMMENDED NOR ADVISED. Any
commercialization of the Software is at the sole risk of the party
or parties engaged in such commercialization. You further agree to
use, reproduce, make derivative works of, display and distribute
the Software in compliance with all applicable governmental laws,
regulations and orders, including without limitation those relating
to export and import control.
5. The Software is provided "AS IS" and neither MGH nor any
contributor to the software (each a "Contributor") shall have any
obligation to provide maintenance, support, updates, enhancements
or modifications thereto. MGH AND ALL CONTRIBUTORS SPECIFICALLY
DISCLAIM ALL EXPRESS AND IMPLIED WARRANTIES OF ANY KIND INCLUDING,
BUT NOT LIMITED TO, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR
A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
MGH OR ANY CONTRIBUTOR BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ARISING IN ANY WAY
RELATED TO THE SOFTWARE, EVEN IF MGH OR ANY CONTRIBUTOR HAS
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. TO THE MAXIMUM
EXTENT NOT PROHIBITED BY LAW OR REGULATION, YOU FURTHER ASSUME ALL
LIABILITY FOR YOUR USE, REPRODUCTION, MAKING OF DERIVATIVE WORKS,
DISPLAY, LICENSE OR DISTRIBUTION OF THE SOFTWARE AND AGREE TO
INDEMNIFY AND HOLD HARMLESS MGH AND ALL CONTRIBUTORS FROM AND
AGAINST ANY AND ALL CLAIMS, SUITS, ACTIONS, DEMANDS AND JUDGMENTS
ARISING THEREFROM.
6. None of the names, logos or trademarks of MGH or any of
MGH's affiliates or any of the Contributors, or any funding
agency, may be used to endorse or promote products produced in
whole or in part by operation of the Software or derived from or
based on the Software without specific prior written permission
from the applicable party.
7. Any use, reproduction or distribution of the Software which is not
in accordance with this Software License shall automatically revoke
all rights granted to you under this Software License and render
Paragraphs 1 and 2 of this Software License null and void.
8. This Software License does not grant any rights in or to any
intellectual property owned by MGH or any Contributor except
those rights expressly granted hereunder.
```
</details>
The whole agreement is on [FreeSurfer's website](https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense).
---
*Rendered with R `r getRversion()` · plotly · ggseg.formats · ggseg.meshes · freesurferformats · misc3d · geometry*