更改ggplot中堆积的直方图条的顺序

时间:2019-10-01 01:37:50

标签: r ggplot2 histogram

我在ggplot中创建了一个堆积的直方图。我想更改堆叠条形的顺序。

我的数据集如下:

head(df)
  difficulty RegularPool SuperPool Item_Pool
1    -3.1185           1        NA   Regular
2    -2.9385           1        NA   Regular
3    -2.8100           1        NA   Regular
4    -2.2797           1        NA   Regular
5    -3.3321           1        NA   Regular
6    -3.0996           1        NA   Regular

我创建了ggplot:

ggplot(data = df, 
    aes(x = difficulty, color = Item_Pool, fill = Item_Pool)) +
    geom_histogram(alpha= 0.5, position = "stack", binwidth = 0.1) +
    geom_vline(xintercept = logit.placement, linetype = "dashed", color = "blue") + #add placement lines
    annotate("text", x = logit.placement, y = 0, angle = 45, label=c("One Below", "Early","Mid", "Late", "One Above"), colour = "blue") + #label placement lines
    xlim(-8, 7) +
    ylab("Number of Testlets") +
    xlab("Testlet Difficulty") +
    ggtitle(paste("Grade ", grade, " Overall Cut = ", item.pool.cut, sep = ""))  

enter image description here

如何使蓝色(“超级”)条位于红色(“常规”)条之上?

1 个答案:

答案 0 :(得分:0)

您可以在致电df之前更改ggplot中因子的顺序

df$Item_Pool = factor(df$Item_Pool,levels=c("Super","Regular"))

按需要的顺序放置水平