通过变量将geom_tile图的y轴阶

时间:2019-03-09 23:21:40

标签: r ggplot2

我正在使用geom_tile可视化随机抽奖

生成数据:

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)

结果是:

Unsorted X axis plot

我真正想要的是y轴由块的前四列(在good_pilots中计算)中的蓝色(即1)排序。

我尝试了scale_y_discrete,但这不是预期的目的:

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

导致: weird looking plot

据我所知,排序似乎工作正常,但是使用scale_y_discrete会导致情节混乱。

1 个答案:

答案 0 :(得分:1)

您可以在此处使用reorder

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

enter image description here

相关问题