ggplot图例:更改自动图例的顺序 [英] ggplot legend: change order of the automatic legend

查看:173
本文介绍了ggplot图例:更改自动图例的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当有多个绘图组时,我在ggplot中的图例顺序中苦苦挣扎.这是一个示例:

 库(ggplot2)库(data.table)数据<-data.table(时间= rep(1:50,4),阻尼时间= rep(c(4,8,12,16),每个= 50),激励= rep(c(rep(0,10),rep(1,10),rep(0,30)),4))数据[,信号:=时间+ .GRP,通过=阻尼时间]data [,dampingtime:= as.factor(dampingtime)] 

我在这里

 >级别(数据$阻尼时间)[1]"4""8""12""16" 

我对

在格里尔(Greor)评论之后,我在因子水平上添加了激励

  data [,dampingtime:= factor(dampingtime,levels = c(levels(dampingtime),"excitation"))]]级别(数据$阻尼时间)[1]"4""8""12""16"激励" 

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

解决方案

您可以通过指定 scale_colour_discrete

来获得所需的顺序.

  ggplot(数据=数据)+geom_line(aes(time,excitation,color ="excitation"))+geom_point(aes(时间,信号,颜色=阻尼时间))+scale_colour_discrete(breaks = c("4","8","12","16",激发"),标签= c(4,8,12,16,激发")) 

I am struggling with the legend order in ggplot when there are several group of plots. Here is an example:

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)]

Here I have

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

which I did accordingly to ggplot legends - change labels, order and title, and I do get the proper legend order when I do

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

my problem is that I want to add the excitation column with an entry to the legend, so I do:

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

In this case, the order is wrong for the number:

following Greor comment, I added excitation to the factor levels

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

but i get exactly the same problem. How should I do to get the proper order ?

解决方案

You can get the order you want by specifying 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"))

这篇关于ggplot图例:更改自动图例的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆