简体   繁体   English

使用 geom_bar(stat="identity") 重新排序 ggplot

[英]reorder ggplot with geom_bar(stat="identity")

I have prepare a dataframe and use a ggplot on him.我准备了一个数据框并在他身上使用了 ggplot。 But the initial order is not respected.但不尊重最初的顺序。 How i can respect this order ?我怎么能尊重这个命令?

Patient Nb_peptides Type_affinite
1       22         563             a
2       22        1040             b
3       22       11139             c
4       24         489             a
5       24        1120             b
6       24       11779             c
7       13         467             a
8       13        1239             b
9       13       14600             c


g_plot <- ggplot(data = nb_peptides_type, 
                 aes(x = reorder(Patient, True_order), 
                     y = Nb_peptides, 
                     fill = Type_affinite)) + 
  geom_bar(stat = "identity")

print(g_plot)

在此处输入图片说明

Please provide stand-alone code to make it easier.请提供独立代码以使其更容易。

I would use levels outside of your plot to reorder factor levels : Is it what you're looking for ?我会使用你的情节之外的levels来重新排序因子水平:这是你要找的吗?

## fake dataframe
df <- data.frame(patient = as.factor(rep((21:30), each=3)), 
                 nb = rpois(30, 1000), 
                 type=sample(letters[1:3], replace =T, size =30))

## initial plot
ggplot(data = df, 
       aes(x = patient, 
           y = nb, 
           fill = type)) + 
  geom_bar(stat = "identity")

## adjust factors levels
True_order <- sample((21:30), 10)
levels(df$patient) <- True_order 


## re-plot
ggplot(data = df, 
       aes(x = patient, 
           y = nb, 
           fill = type)) + 
  geom_bar(stat = "identity")

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

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