简体   繁体   English

按变量排序 geom_tile 图的 y 轴

[英]order y-axis of geom_tile plot by variable

I am using geom_tile to visualize random draws我正在使用 geom_tile 来可视化随机绘制

Generate data:生成数据:

set.seed(1)
df= crossing(sim=1:10,part= 1:10)
df$result = sample(c(1,0),size = nrow(df), replace=T)
df = df %>% 
  group_by(sim)%>%
  # find out how many successful (1) pilots there were in the first 4 participants
  summarize(good_pilots = sum(result[1:4])) %>% 
  arrange(good_pilots) %>%
  ungroup() %>%
  # add this back into full dataframe
  full_join(df) 
# plot data
plot = ggplot(df, aes( y=factor(sim), x=part)) +
    geom_tile(aes(fill = factor(result)), colour = "black", 
              show.legend = T)+

  scale_fill_manual(values=c("lightgrey", "darkblue"))+# c(0,1)
  theme(panel.border = element_rect(size = 2),
              plot.title = element_text(size = rel(1.2)),
              axis.text = element_blank(),
              axis.title = element_blank(),
              axis.ticks = element_blank(),
              legend.title = element_blank(),
              legend.position = "right")+ theme_classic()+ coord_fixed(ratio=1)

This results in:这导致:

未排序的 X 轴图

What I actually want is the y axis to be ordered by the # of blue (ie 1's) in the first four columns of the block (which is calculated in good_pilots ).我真正想要的是在块的前四列(在good_pilots计算)中按蓝色(即 1 的)# 排序的 y 轴。

I tried scale_y_discrete but that cannot be what is intended:我试过scale_y_discrete但这不可能是预期的:

plot + scale_y_discrete(limits=df$sim[order(df$good_pilots)])

resulting in:导致: 诡异的剧情

From what I can tell it seems like the ordering worked correctly, but using scale_y_discrete caused the plot to be messed up.据我所知,排序似乎工作正常,但使用 scale_y_discrete 导致情节混乱。

You can use reorder here您可以在此处使用reorder

ggplot(df, aes(y = reorder(sim, good_pilots), x = part)) +
  ...

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM