Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
531 views
in Technique[技术] by (71.8m points)

r - Geom tile collapses along Y-axis when adding coord_equal()

I have a time series data (currently on monthly frequency) from 2014 up to 2020. That means at most 84 monthly values.

For example when plotting (two of categories from the time series data) using geom_tile, I would have a visual below.

ID <- rep(c('A','B','C'),each = 84)
n <- rep(round(runif(84,1,4)), 3)
datetime <- rep(seq(as.POSIXct("2014-01-01"), as.POSIXct("2020-12-01"), by="month"), 3)
df <- tibble(ID,n, datetime)
ggplot(df ,
       aes(x=datetime,y=ID,fill=n))+
  geom_tile() + 
  scale_y_discrete(expand=c(0,0)) + 
  scale_fill_viridis() 

enter image description here

I want the rectangle to be a square, so I add on coord_equal() to my ggplot, but somehow the heatmap collapses along the Y-axis

ggplot(df ,
       aes(x=datetime,y=ID,fill=n))+
  geom_tile() + 
  scale_y_discrete(expand=c(0,0)) + 
  scale_fill_viridis() + coord_equal()

enter image description here

The expectation is something like below. As you can see, the squares are of equal size across.

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The reason for why the tile map collapses are well explained in the excellent answer by @eipi10 on the same issue. As the reason is that one unit on the x-axis is by default translated into one unit on the y-axis you could prevent the collapsing of your tile map by setting the conversion ratio according to the ranges of the x and y scale:

ID <- rep(c('A','B','C'),each = 84)
n <- rep(round(runif(84,1,4)), 3)
datetime <- rep(seq(as.POSIXct("2014-01-01"), as.POSIXct("2020-12-01"), by="month"), 3)
df <- data.frame(ID,n, datetime)

library(ggplot2)
library(viridis)
#> Loading required package: viridisLite
ggplot(df ,
       aes(x=datetime,y=ID,fill=n))+
  geom_tile() + 
  scale_y_discrete(expand=c(0,0)) + 
  scale_fill_viridis() +
  coord_equal(ratio = diff(range(as.numeric(datetime))) / length(unique(ID)))


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...