是否可以在ggplot2中创建具有各种颜色的平滑的大geom_line()?

时间:2020-06-09 14:22:08

标签: r ggplot2

我本来打算使用功能区来实现此功能,但是功能区给我一个“功能区内美学无法改变”的错误。我尝试了geom_smooth,geom_ribbon和geom_line,但它们都无法满足我的需求。下面需要的图片是我所需要的,除了我希望线条之间的正方形连接处将颜色更改为垂直,齐平或圆形。

我已经看过这些帖子:

Shade Fill or Cover Area Density Under Curve

R ggplot Issue When Using Group Interaction

我还尝试了几种不同的方式使用组。我应该提到,我一般对ggplot2和R还是陌生的,因此任何帮助或可能的途径都将不胜感激。我一直在使用这些资源,您可能会发现这些资源对于解决此问题或您自己的问题很有用:

R For Data Science

GGPlot2: Elegant Graphics For Data Analysis

GGPlot2 Documentation

R Cookbook

代码:

library(ggplot2)

pdf("ggplot_learning.pdf")

data <- data.frame(
  xvals = c(0:5),
  yvals = c(4, 5, 4.5, 5.5, 5, 6),
  lower = c(3.9, 4.9, 4.4, 5.4, 4.9, 5.9),
  upper = c(4.1, 5.1, 4.6, 5.6, 5.1, 6.1)
)


plot <- ggplot(data, aes(xvals, yvals, ymax = 8, xmax = 8)) + 
  geom_line(aes(color = yvals, alpha = .3), lwd = 10) + 
  geom_line(aes(color = yvals)) + 
  theme(legend.position = "none")

print(plot)

到目前为止我所拥有的:

Graph With Rough Idea of What I Need

2 个答案:

答案 0 :(得分:3)

我不确定,但也许是这样:

data2 <- rbind(data, data[-1,]) 
data2 <- data2[order(data2$xvals),]
data2$n <- factor(head(rep(1:6, each=2),-1))

ggplot(data2, aes(xvals, yvals,color=n, fill=n, group=n)) + 
  geom_line() + 
  geom_ribbon(aes(ymin=lower, ymax=upper), alpha = 0.5)

enter image description here

由于需要geom_ribbon函数的组,因此需要指定每个部分。因此,从0到1,从1到2 ... 因此,我两次rbind数据,根据x排序并添加分组因子n

答案 1 :(得分:1)

使用geom_path时,这看起来要好一些 ,但是当颜色改变时,似乎忽略了linejoin =参数:

ggplot(data, aes(x = xvals, y = yvals)) + 
  geom_path(aes(color = yvals, alpha = .3), lwd = 10,
            lineend="round",linejoin="miter") + 
  geom_line(aes(color = yvals)) + 
  theme(legend.position = "none")

enter image description here

相关问题