根据y值连续颜色的geom_line

时间:2014-09-18 06:47:57

标签: r ggplot2

如果你看这个

enter image description here

ggplot(mtcars,aes(x=disp,y=mpg,colour=mpg))+geom_line()

你会看到线条颜色根据相应的y值而变化,这是我想要的,但只是逐段。我希望颜色根据y值连续变化。有什么简单的方法吗?

3 个答案:

答案 0 :(得分:7)

一种可能的想法是使用插值来创建更多的x值和y值,从而使颜色更加连续。我使用approx来“线性插入给定的数据点”。这是一个更简单的数据集的例子:

# original data and corresponding plot
df <- data.frame(x = 1:3, y = c(3, 1, 4))
library(ggplot2)
ggplot(data = df, aes(x = x, y = y, colour = y)) +
  geom_line(size = 3)

enter image description here

# interpolation to make 'more values' and a smoother colour gradient 
vals <- approx(x = df$x, y = df$y)
df2 <- data.frame(x = vals$x, y = vals$y)

ggplot(data = df2, aes(x = x, y = y, colour = y)) +
  geom_line(size = 3)

enter image description here

如果您希望渐变更平滑,可以使用n中的approx参数来调整要创建的点数(“插值在n同等地进行跨越区间[min(x), max(x)]“)的间隔点。使用更多的值,或许geom_point可以提供更平滑的外观:

vals <- approx(x = df$x, y = df$y, n = 500)
df2 <- data.frame(x = vals$x, y = vals$y)
ggplot(data = df2, aes(x = x, y = y, colour = y)) +
  geom_point(size = 3)

答案 1 :(得分:3)

由于ggplot2 v0.8.5可以将geom_linegeom_path与不同的lineend选项一起使用(目前有三个选项:roundbuttsquare)。选择取决于数据的性质。

round可以在锋利的边缘上工作(例如在给定的OP数据中):

library(ggplot2)
ggplot(mtcars, aes(disp, mpg, color = mpg)) +
  geom_line(size = 3, lineend = "round")

enter image description here

square将对更连续变量起作用:

df <- data.frame(x = seq(0, 100, 10), y = seq(0, 100, 10) ^ 2)
ggplot(data = df, aes(x = x, y = y, colour = y)) +
  geom_path(size = 3, lineend = "square")

enter image description here

答案 2 :(得分:0)

也许这对你有用:

library(dplyr)
library(ggplot2)

my_mtcars <- 
  mtcars %>%
  mutate(my_colors = cut(disp, breaks = c(0, 130, 200, 400, Inf)))

ggplot(my_mtcars, aes(x = disp, y = mpg, col = mpg)) + 
  geom_line() + facet_wrap(~ my_colors, scales = 'free_x')