ggplot2图形与标签不匹配

时间:2016-01-27 17:26:17

标签: r ggplot2 bar-chart

我无法按照轴中出现的顺序制作图表。

我以各种可能的方式改变了因素的水平(重新定位,水平,......)。当我绘制主图时,它们的顺序正确,标签也是正确的顺序,但是箱图是按字母顺序排列的,一个主图的内容是用另一个切换的(按字母顺序排列)。

Image of the problem

以下代码效果很好:

a <- ggplot(data, aes(x = GroupX, y = Score, fill=GroupX, order=GroupX))+
scale_fill_manual(values=colours) +
  theme(axis.text.x = element_text(angle = 45, hjust = 1),
    legend.position="none",
    panel.background = element_rect(fill = "white"),
    panel.grid.major = element_line(colour = "gray95"),
    panel.border = element_rect(fill = NA, colour = "black", size = 2))+
ylab("Lesion")+
xlab("")+
guides(colour=FALSE)+
facet_wrap(~ Portion)

以下代码生成正确的方面:

enter image description here

当我尝试使用:

a + geom_boxplot()

条形图的顺序和整个图形按字母顺序显示。

级别格式正确。我无法弄清楚如何纠正这一点。

  • 可重复的示例

数据集:

structure(list(Level = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 
4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 
5L, 5L, 5L, 5L, 5L, 5L, 5L), .Label = c("A", "B", "C", "D", "E"
), class = "factor"), Factor = structure(c(1L, 1L, 3L, 3L, 2L, 
2L, 2L, 1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 1L, 1L, 1L, 2L, 2L, 2L, 
3L, 3L, 1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 1L, 1L, 1L, 1L, 2L, 
2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L), .Label = c("X", "Y", "Z"
), class = "factor"), Valor = c(12, 11, 20, 15, 2, 5, 21, 21, 
51, 1, 2, 15, 2, 56, 5, 21, 5, 12, 21, 15, 23, 5, 4, 55, 1, 2, 
89, 2, 4, 12, 23, 10, 12, 51, 45, 2, 15, 32, 21, 15, 4, 5, 45, 
45, 2, 14)), .Names = c("Level", "Factor", "Valor"), row.names = c(NA, 
-46L), class = "data.frame")

代码无需更改订单:

a <- ggplot(data, aes(x = Level, y = Valor, fill=Factor, order=Level)) +
     facet_wrap(~ Factor)
a + geom_boxplot()

当我们设定因素时 - 快速方式:

levels(data$Factor) <- c("Y", "Z", "X")
levels(data$Level) <- c("D", "C", "A", "B", "E")

标签已更改,但情节不会改变。

1 个答案:

答案 0 :(得分:1)

您尝试使用

更改关卡的顺序
levels(data$Factor) <- c("Y", "Z", "X")
levels(data$Level) <- c("D", "C", "A", "B", "E")

但是,这只会更改级别的名称。那么之前的第一个级别现在将被称为“Y”,但它仍然是第一级,并且仍然存在与之相关的相同数据。但您可以重新定义因子以更改顺序。所以这应该给你预期的结果:

data$Factor <- factor(data$Factor, c("Y", "Z", "X"))
data$Level <- factor(data$Level, c("D", "C", "A", "B", "E"))

让我告诉你这有什么影响。首先,我按原样绘制数据:

enter image description here

然后,我重新定义了这些因素并再次绘制:

data$Factor <- factor(data$Factor, c("Y", "Z", "X"))
data$Level <- factor(data$Level, c("D", "C", "A", "B", "E"))
ggplot(data, aes(x = Level, y = Valor, fill=Factor)) +
   facet_wrap(~ Factor) + geom_boxplot()

enter image description here