ggplot循环添加曲线失败,但每次只能使用一个 [英] ggplot loop adding curves fails, but works one at a time

查看:302
本文介绍了ggplot循环添加曲线失败,但每次只能使用一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的循环,试图使用 ggplot 在同一个图上绘制四条曲线。这里是代码:

  df = data.frame(x = 0:10/10)
gg = ggplot (df)
(t in 4:1/4)
gg = gg + geom_path(aes(x,x ^ t))
gg

当我运行它时,它只显示最后一个图。如果我一次添加一个,例如:

  df = data.frame(x = 0:10/10)
gg = ggplot(df)
gg = gg + geom_path(aes(x,x ^ 1.00))
gg = gg + geom_path(aes(x,x ^ 0.75))
gg = gg + geom_path(aes(x,x ^ 0.50))
gg = gg + geom_path(aes(x,x ^ 0.25))
gg

工作得很好。有人可以解释这种魔术吗?

解决方案

注意,这里使用 geom_line()是因为它按照x轴上的变量顺序连接观察值。 geom_path()按照它们在数据中出现的顺序连接观察值。

不同的曲线可以颜色代码:

 #连续缩放比例
gg + aes(color = exp)

 #离散比例
gg + aes(color = factor(exp))



请注意,通过在 aes()默认情况下创建相应的图例。


I have a very simple loop trying to draw four curves on the same graph using ggplot. Here is the code:

  df = data.frame(x=0:10/10)
  gg = ggplot(df)
  for (t in 4:1/4)
      gg = gg + geom_path(aes(x,x^t))
  gg  

When I run it, it only shows the last graph. If I add them one at a time, eg:

  df = data.frame(x=0:10/10)
  gg = ggplot(df)
  gg = gg + geom_path(aes(x,x^1.00))
  gg = gg + geom_path(aes(x,x^0.75))
  gg = gg + geom_path(aes(x,x^0.50))
  gg = gg + geom_path(aes(x,x^0.25))
  gg

it works just fine. Can someone explain the magic?

解决方案

Baptiste suggested to create the entire data.frame with all variables first, and then plot it (preferably in long format). The answer provided by Gene creates the data in wide format requiring to loop over the columns.

The code below creates the data in long format and plots all curves in one call:

# create data in long format
df <- expand.grid(x = 0:10/10, exp = 1:4/4)
df$y <- df$x^df$exp

# plot
library(ggplot2)
gg <- ggplot(df, aes(x, y, group = exp)) + geom_line()
gg

Note that geom_line() is used here because it connects the observations in order of the variable on the x axis. geom_path() connects the observations in the order in which they appear in the data.

The different curves can be colour-coded as well:

# continous scale
gg + aes(colour = exp)

# discrete scale
gg + aes(colour = factor(exp))

Note that by including the colour aesthetic in the call to aes() an appropriate legend is created by default.

这篇关于ggplot循环添加曲线失败,但每次只能使用一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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