Home Articles

ggplot图例:更改自动图例的顺序

Asked
Viewed 41 times
2

当有几组情节时,我正在与ggplot中的传奇顺序挣扎 . 这是一个例子:

library(ggplot2)
library(data.table)
data <- data.table(time = rep(1:50,4),dampingtime = rep(c(4,8,12,16),each = 50),
                   excitation = rep(c(rep(0,10),rep(1,10),rep(0,30)),4))
data[,signal := time + .GRP, by = dampingtime]
data[,dampingtime := as.factor(dampingtime)]

我有

> levels(data$dampingtime)
[1] "4"  "8"  "12" "16"

我做了相应的ggplot legends - change labels, order and title,当我这样做时,我确实得到了正确的传奇顺序

ggplot(data = data) +
geom_point(aes(time,signal,color = dampingtime))

我的问题是我想添加激励列,并在图例中添加一个条目,所以我这样做:

ggplot(data = data) +
geom_line(aes(time,excitation,color = "excitation")) +
geom_point(aes(time,signal,color = dampingtime))

在这种情况下,订单的顺序是错误的:
enter image description here

在Greor评论之后,我在因子水平上加入了激励

data[,dampingtime := factor(dampingtime,levels = c(levels(dampingtime),"excitation"))]
levels(data$dampingtime)
[1] "4"          "8"          "12"         "16"         "excitation"

但我得到完全相同的问题 . 我该怎么做才能得到正确的订单?

1 Answer

  • 1

    您可以通过指定 scale_colour_discrete 获得所需的订单

    ggplot(data = data) +
     geom_line(aes(time,excitation,color = "excitation")) +
     geom_point(aes(time,signal,color = dampingtime)) +
     scale_colour_discrete(breaks=c("4","8","12","16","excitation"), labels=c(4,8,12,16,"excitation"))
    

Related