在同一张图上用不同颜色绘制向量的不同部分 [英] Plot different parts of a vector with different colors on the same graph

查看:69
本文介绍了在同一张图上用不同颜色绘制向量的不同部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从标题假设这个向量和绘图:

plot(rnorm(200,5,2),type="l")

返回这个图

我想知道是否有办法让它的前半部分变成蓝色 col="blue" 而其余部分变成红色 "col="红色".

Matlab 中的类似问题而不是 R:

我们还可以使用

注意蓝线和红线是断开的.不确定这是否重要,但如果你想绘制一条连续的线,这里有一个解决方法

As from the title suppose this vector and plot:

plot(rnorm(200,5,2),type="l")

This returns this plot

What i would like to know is whether there is a way to make the first half of it to be in blue col="blue" and the rest of it to be in red "col="red".

Similar question BUT in Matlab not R: Here

解决方案

Not a base R solution, but I think this is how to plot it using . It is necessary to prepare a data frame to plot the data.

set.seed(1234)

vec <- rnorm(200,5,2)

dat <- data.frame(Value = vec)
dat$Group <- as.character(rep(c(1, 2), each = 100))
dat$Index <- 1:200

library(ggplot2)

ggplot(dat, aes(x = Index, y = Value)) +
  geom_line(aes(color = Group)) +
  scale_color_manual(values = c("blue", "red")) +
  theme_classic()

We can also use the package with the same data frame.

library(lattice)
xyplot(Value ~ Index, data = dat, type = 'l', groups = Group, col = c("blue", "red"))

Notice that the blue line and red line are disconnected. Not sure if this is important, but if you want to plot a continuous line, here is a workaround in . The idea is to subset the data frame for the second half, plot the entire data frame with color as blue, and then plot the second data frame with color as red.

dat2 <- dat[dat$Index %in% 101:200, ]

ggplot(dat, aes(x = Index, y = Value)) +
  geom_line(color = "blue") +
  geom_line(data = dat2, aes(x = Index, y = Value), color = "red") +
  theme_classic()

这篇关于在同一张图上用不同颜色绘制向量的不同部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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