Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a continuous 1d heatmap in R

Tags:

r

ggplot2

heatmap

For lack of a better name, I want to create a continous 1-d heatmap in R, i.e. a 1-d version of this question

Toy data to use:

df <- data.frame(x=1:20,
  freq=c(8, 7, 5, 6, 10, 4, 2, 9, 3, 10, 1, 8, 4, 7, 2, 6, 7, 6, 9, 9))

I can create a crude gridded output using

ggplot(data=df, aes(x=x, y=1)) + geom_tile(aes(fill=freq))

but similar to the other question, I'd like to have a smooth colour transition instead. Unfortunately, I don't understand the 2-d answer well enough to adapt it to 1-d.

like image 776
Ricky Avatar asked Aug 01 '15 09:08

Ricky


People also ask

Can you make a heat map in R?

heatmap() function in R Language is used to plot a heatmap. Heatmap is defined as a graphical representation of data using colors to visualize the value of the matrix.

Can you make a heatmap in ggplot2?

To create a heatmap with the melted data so produced, we use geom_tile() function of the ggplot2 library. It is essentially used to create heatmaps.

What package is heatmap in R?

Complex heatmap. ComplexHeatmap is an R/bioconductor package, developed by Zuguang Gu, which provides a flexible solution to arrange and annotate multiple heatmaps. It allows also to visualize the association between different data from different sources.


1 Answers

Since your data are frequencies, it makes more sense to me to present them as raw data:

df2 <- unlist(apply(df, 1, function(x) rep(x[1], x[2])))

Then I would use the kernel density to create a smooth representation of your categories:

df2 <- density(df2, adjust = 1)
df2 <- data.frame(x = df2$x, y = df2$y) #shouldn't there be an as.data.frame method for this?

And then plot as tiles:

ggplot(df2, aes(x = x, y = 1, fill = y)) + geom_tile()

You can use the adjust argument in the density call to change the level of smoothing.

Adjust 1 (default): plot1 Adjust 0.5: plot2 Adjust 0.3: plot3

like image 63
Axeman Avatar answered Sep 20 '22 11:09

Axeman