多个曲线与单个图中的不同域(使用ggplot2) [英] Multiple Curves With Different Domains in a Single Plot ( with ggplot2)

查看:155
本文介绍了多个曲线与单个图中的不同域(使用ggplot2)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  library(ggplot2)
eq = function(x){x ^ -1}
ggplot(data.frame(x = c(-6 ,6)),aes(x = x,y = eq(x)))+
geom_line(data = as.data.frame(curve from = -6,to = - 01,eq)) )+
geom_line(data = as.data.frame(曲线(从= .01,到= 6,eq)))

我试图制作一个单一的情节,这段代码给了我想要的情节,但有两个额外的情节,每个情节都有一个情节。我不明白为什么这些额外的两个地块正在创建。 这就是为什么你得到额外的阴谋。为避免出现这种情况,您可以在绘制之前创建一个数据框,并在 geom_line 中对它进行子集化:

  library(ggplot2)
eq = function(x){x ^ -1}
df < - data.frame(x = seq(-6,6, 0.01),y = eq(seq(-6,6,0.01)))
ggplot(df)+
geom_line(data = subset(df,x <= - 01),aes(x = x,y = y))+
geom_line(data = subset(df,x> =。01),aes(x = x,y = y))


library("ggplot2")
eq = function(x){x^-1}
ggplot(data.frame(x=c(-6,6)), aes(x = x, y=eq(x)))+
    geom_line(data=as.data.frame(curve(from=-6, to=-.01, eq)))+
    geom_line(data=as.data.frame(curve(from=.01, to=6, eq)))

I am trying to produce a single plot, and this code gives me the plot I want, but with two additional plots, one with each geom_line. I don't understand why those additional two plots are being created.

解决方案

As @shayaa noted in the comments, curve itself generates plots, which is why you are getting the extra plots. To avoid this, you can just create a dataframe before you plot, and subset it in geom_line:

library("ggplot2")
eq = function(x){x^-1}
df <- data.frame(x =seq(-6, 6, 0.01), y = eq(seq(-6, 6, 0.01)))
ggplot(df) +
  geom_line(data=subset(df, x<=-.01), aes(x = x, y = y)) +
  geom_line(data=subset(df, x>=.01), aes(x = x, y = y))

这篇关于多个曲线与单个图中的不同域(使用ggplot2)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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