要在ggplot中按形状添加图例(在第二个问题之后添加:计算数值导数) [英] To add a legend by shape in ggplot ( added 2nd question after: to calculate numeric deriv)

查看:144
本文介绍了要在ggplot中按形状添加图例(在第二个问题之后添加:计算数值导数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试按形状添加图例.

I try to add a legend by shape.

尽管有两个形状和两个y轴,但我有一个带有一个图例的图形.

I have a graphic with one legend despite of two shapes and two y axes.

我想用两个图例,每个y轴一个.

and I would like it with two group of legend, one for each y axe.

问题2在之后添加

2)实际上,它是用于显示数字导数,即用一个函数来代替我的calc=t/10

2) In fact it was for display numeric deriv, ie to replace my calc=t/10 by a function doing

f(x)=(t_n-t_n-1)/(date_time_n/date_time_n -1)

f(x)=(t_n-t_n-1)/(date_time_n / date_time_n -1)

其中f(x)是我的计算列.

where f(x) will be my calc column.

但是我想我不理解R中的派生.

but I think I don't understand derive in R.

我的下一个问题:编辑结束

这是我的代表

library(tidyverse)
library(ggplot2)

datas<-data.frame(
  t = c(
    50 + c(0, cumsum(runif(9, -7, 7))),
    70 + c(0, cumsum(runif(9, -10, 10)))
  ),
  orig=c(rep("s1",10),rep("s2",10)),
  date_heure = rep(
    seq(from=as.POSIXct("2012-1-1 0:00", tz="UTC"),by="hour", length=10) ,
    2
  ) 
)


datas<- (datas 
         %>% mutate (
           calc=t/10
         )
)

(
  ggplot(datas) 
  +   geom_line(aes(x = date_heure, y = t,colour=orig))
  +   geom_line(aes(x = date_heure, y = calc, color=orig))
  + scale_y_continuous(
    name = "t", 
    sec.axis = sec_axis(trans=~(range(datas$calc)), 
                        name = "calc ")
  )
  + geom_point(mapping = aes(x = date_heure, y = calc,color=orig), shape = 21, fill = "white") 
)

推荐答案

您可以使用linetype属性,并手动分配图例名称和线条颜色,如下所示:

You can use the linetype property and manually assign the legend names and line colors, as follows:

(
  ggplot(datas) 
  +   geom_line(mapping=aes(x = date_heure, y = t, color=orig, linetype = "s1"))
  +   geom_line(mapping=aes(x = date_heure, y = calc, color=orig, linetype = "s2"))
  +   scale_y_continuous(name = "t", sec.axis = sec_axis(trans=~(range(datas$calc)), name = "calc"))
  +   geom_point(mapping = aes(x = date_heure, y = calc, color=orig), shape = 21, fill = "white")
  +   scale_color_manual(name = "calc", values=c("red", "blue"))
  +   scale_linetype_manual(name = "orig", values = c('solid', 'solid'), 
                            guide = guide_legend(override.aes = list(colour=c("red", "blue"))))

)

这将产生以下情节:

希望有帮助.

这篇关于要在ggplot中按形状添加图例(在第二个问题之后添加:计算数值导数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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