在ggplot2

时间:2018-05-28 20:59:23

标签: r ggplot2 label facet-grid

我的数据框如下

> dput(dat2)
structure(list(School = structure(c(2L, 2L, 2L, 1L, 1L, 1L, 3L, 
3L, 3L), .Label = c("School1", "School2", "School3"), class = "factor"), 
    Year = c(2015L, 2014L, 2013L, 2015L, 2014L, 2013L, 2015L, 
    2014L, 2013L), Rate = c(80L, 90L, 11L, 70L, 50L, 30L, 60L, 
    50L, 40L), Order = c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L), 
    Order2 = c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), Order3 = structure(c(NA_integer_, 
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_, 
    NA_integer_, NA_integer_, NA_integer_), .Label = c("School2", 
    "School1", "School3"), class = "factor")), .Names = c("School", 
"Year", "Rate", "Order", "Order2", "Order3"), row.names = c(NA, 
-9L), class = c("tbl_df", "tbl", "data.frame"))

  School   Year  Rate Order Order2
  <fct>   <int> <int> <int>  <int>
1 School2  2015    80     1      1
2 School2  2014    90     1      2
3 School2  2013    11     1      3
4 School1  2015    70     2      1
5 School1  2014    50     2      2
6 School1  2013    30     2      3
7 School3  2015    60     3      1
8 School3  2014    50     3      2
9 School3  2013    40     3      3

我使用两个名为Order和Order2的列来指定我的数据绘制方式。我使用以下代码创建一个构面网格。

p <- ggplot(dat2, aes(x=reorder(Year,Order2), Rate)) + geom_bar(stat = "identity", width = 0.5)
p + facet_grid(. ~Order)

给出以下网格。

enter image description here

这是我想要的顺序(根据订单变量的值) School2 - &gt; School1 - &gt; School3。

我正在尝试修改构面标签以显示学校名称而不是Order列中的值。如果我在facet_grid中使用了School这样的列,例如

p <- ggplot(dat2, aes(x=reorder(Year,Order2), Rate)) + geom_bar(stat = "identity", width = 0.5)
p + facet_grid(. ~School)

我得到以下图表。 enter image description here

所以标签正是我想要的,但顺序不是基于Order列中的值,而是基于School列的字母顺序。

请帮助我了解如何使用第一个图表中显示的“订单”列中的值保留构面的顺序,但是将构面标签更改为“学校”列中的值。我还看了一些使用贴标机功能的例子,但它们都依赖于手动指定标签。此数据集是一个示例,实际将有更多数据,因此我不想对标签值进行硬编码并探查ggplot2 / facet_grid中是否有一个函数可能允许我为facet_grid标签指定一列。

1 个答案:

答案 0 :(得分:0)

使用forcatsdplyr

 library(dplyr)
 library(forcats)
 dat2 %>%
     mutate(School = fct_relevel(School, c("School2","School1","School3"))) %>%
     ggplot(aes(x=reorder(Year,Order2), Rate), labels = c("School1","School2","School3")) +
     geom_bar(stat = "identity", width = 0.5) +
     facet_grid(. ~School)

enter image description here