gpt4 book ai didi

r - ggplot 热图网格线格式 geom_tile 和 geom_rect

转载 作者:行者123 更新时间:2023-12-03 16:21:17 27 4
gpt4 key购买 nike

几天来,我一直致力于创建热图,但无法使网格线的最终格式正常工作。请参阅下面的代码和附图。我想要做的是使用 geom_tile() 沿着热图的图块对齐网格线,以便每个图块以框方式填充网格内部。我能够使用 geom_raster() 对齐网格线,但 y 轴标签在瓷砖的顶部或底部打勾,但我需要它在中心打勾(参见红色突出显示),我也无法让 geom_raster 换行瓷砖周围的白线边框,因此色块在我的原始数据集中看起来有点困惑。对格式代码的任何帮助将不胜感激。非常感谢!

#The data set in long format 


y<- c("A","A","A","A","B","B","B","B","B","C","C","C","D","D","D")
x<- c("2020-03-01","2020-03-15","2020-03-18","2020-03-18","2020-03-01","2020-03-01","2020-03-01","2020-03-01","2020-03-05","2020-03-06","2020-03-05","2020-03-05","2020-03-20","2020-03-20","2020-03-21")
v<-data.frame(y,x)

#approach 1 using geom_tile but gridline does not align with borders of the tiles
v%>%
count(y,x,drop=FALSE)%>%
arrange(n)%>%
ggplot(aes(x=x,y=fct_reorder(y,n,sum)))+
geom_tile(aes(fill=n),color="white", size=0.25)

need tile borders to align with gridline

我试过从 another post 运行类似的代码但我无法让它正常运行。我认为因为我的 x 变量是 y 变量的计数变量,所以不能格式化为因子变量以在 geom_rect() 中指定 xmin 和 xmax
#approach 2 using geom_raster but y-axis label can't tick at the center of tiles and there's no border around the tile to differentiate between tiles. 

v%>%
count(y,x,drop=FALSE)%>%
arrange(n)%>%
ggplot()+
geom_raster(aes(x=x,y=fct_reorder(y,n,sum),fill=n),hjust=0,vjust=0)

need y axis label to tick at center of tiles and need border around the tiles

最佳答案

我认为保持刻度线和网格线在它们所在的位置是有意义的。为了仍然实现您正在寻找的内容,我建议您扩展数据以包含所有可能的组合,只需设置 na.value到中性填充颜色:

# all possible combinations
all <- v %>% expand(y, x)

# join with all, n will be NA for obs. in all that are not present in v
v = v %>% group_by_at(vars(y, x)) %>%
summarize(n = n()) %>% right_join(all)

ggplot(data = v,
aes(x=x, y=fct_reorder(y,n, function(x) sum(x, na.rm = T))))+ # note that you must account for the NA values now
geom_tile(aes(fill=n), color="white",
size=0.25) +
scale_fill_continuous(na.value = 'grey90') +
scale_x_discrete(expand = c(0,0)) +
scale_y_discrete(expand = c(0,0))

关于r - ggplot 热图网格线格式 geom_tile 和 geom_rect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61968942/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com