在ggplot2中重新排序图例

时间:2018-02-13 21:29:27

标签: r ggplot2 legend

我试图在ggplot中重新排序我的传奇,以便首先列出“控制”,而不是将浓度安排在低 - 高。我已经按照我想要的图例顺序放置了我的数据集并尝试了scale_fill_discrete。

你能发现任何不起作用的原因吗?

p <- ggplot(data = deviation_cloth, aes(x = day, y = Deviation))+
  geom_line(aes(color = factor(Labels)), size = 1)+
  scale_fill_discrete(breaks = c("control", "1E-3","0.01", "0.1", "1", "10"))

p + labs(color = "Conc", x = "Day", y = "Result ")

default String hash codes

2 个答案:

答案 0 :(得分:1)

有几件事:前面提到的评论,但你将标签映射为颜色,但是然后使用缩放功能进行填充。因为它是一条线,颜色是有道理的;只需更改为scale_color_discrete

第二件事是你想要限制参数,而不是休息参数。通过设置限制,您可以定义所包含的类别以及它们的显示顺序。您可以更改为scale_color_discrete(limits = c("control", "1E-3","0.01", "0.1", "1", "10"))

或者,您可以使用有序因子并根据需要排列该变量的级别。来自fct_relevel包的forcats是tidyverse的一部分,可以轻松完成此操作而无需手动提供所有级别。

答案 1 :(得分:0)

也许这......

library(tidyverse)

df <-
  data_frame(
    x = c(1, 2, 3, 1, 2, 3, 1, 2, 3),
    y = c(2, 3, 4, 3, 4, 5, 4, 5, 6),
    z = c("a", "a", "a", "b", "b", "b", "c", "c", "c")
  )

ggplot(df, aes(x, y, colour = z)) +
  geom_line()

ggplot(df, aes(x, y, colour = z)) +
  geom_line() +
  guides(colour = guide_legend(reverse = T))