Create a continuous 1d card in R

Due to the lack of a better name, I want to create a continuous 1-dimensional memory card in R, i.e. a 1-dimensional 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 rough output grid using

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

but it seems like another question, I would like to have a smooth transition of color. Unfortunately, I do not understand the 2nd answer well enough to adapt it to the 1st.

+4
source share
2 answers

I'm not quite sure that I understood what you want, but this is an attempt to solve [what I think] your problem:

Firstly, you have a very short vector, and the changes to freq very dramatic, so this will create a very β€œtile” sense of plot. You must first address this issue. My approach uses spline interpolation:

  newdf=data.frame(x=spline(df)[[1]],freq=spline(df)[[2]],y=rep(1,times=3*length(df$x))) 

Note that I also created the vector y in the data frame.

Now it can be built using lattice levelplot :

 levelplot(freq~x*y,data=newdf) 

Which gives a smoother plot (as I understand it, this is what you need). It can also be applied using ggplot :

 ggplot(newdf,aes(x=x,y=y,fill=freq))+geom_tile() 

=========== EDIT ADD =============

Note that you can control the new vector length with the spline n argument, which makes for a smoother transition ( spline(df,n=100)[[1]] ). If you run this option, be sure to edit the times you repeat 1 in y definition !!. The default value of n is 3x the length of the input vector.

+1
source

Since your data is frequencies, it seems to me more reasonable to present it as raw data:

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

Then I would use 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 draw as tiles:

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

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

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

+3
source

All Articles