以自定义颜色,图例等方式在ggplot中绘制多个数据系列的正确方法 [英] Proper way to plot multiple data series in ggplot with custom colors, legend etc
问题描述
我想逐步构建一个包含多个不同长度数据序列的图。我的目标是能够控制每个数据系列的外观,
给它们自定义名称
并拥有适当的图例。我的数据系列具有不同的长度,所以
我不能将它们放在一个数据框中。
在下面的代码中,我预计有4行:最短的将是红色,接下来的将分别是蓝色,绿色和黑色
<$ ('红','蓝','绿','绿','蓝','绿'), (长度(颜色))){
x< - seq(1,2 * i)
y< - x * i + rnorm(' (x,y),数据= df,颜色=(x,y)颜色[i])+
geom_line(aes(x,y),data = df,color = colors [i])
}
print(plt)
这就是我得到的。
我该如何给线条命名并显示图例?
是否有更好的方法来实现我的目标?
执行此操作的方法是创建单个数据 c $ c
$ lt; -c('red','blue','green','black')
dat.t(12345)
color< ; - lapply(seq_along(colors),function(i)){
x< - seq(1,2 * i)
data.frame(
series = colors [i],
x = x,
y = x * i + rnorm(length(x))
)}
)
dat < - do.call(rbind,dat)
现在绘图
ggplot(dat,aes(x,y,color = series))+ geom_line()
I want to incrementally build a plot that contains several data series of different lengths. My goal is to be able to control the appearance of each data series, give them custom names and to have appropriate legends. My data series are of different lengths, so I cannot put them in a single dataframe. In the code below I expect 4 lines: the shortest will be red, the next ones will be blue, green and black respectively
library(ggplot2)
set.seed(12345)
plt <- ggplot()
colors <- c('red', 'blue', 'green', 'black')
for(i in seq(length(colors))) {
x <- seq(1, 2*i)
y <- x * i + rnorm(length(x))
df <- data.frame(x=x, y=y)
plt <- plt + geom_point(aes(x, y), data=df, color=colors[i]) +
geom_line(aes(x, y), data=df, color=colors[i])
}
print(plt)
This is what I get.
How can I give names to the lines and display a legend? Is there a better way to acheive my goal?
The way to do this is to create a single data frame in long format:
Like this:
library(ggplot2)
set.seed(12345)
colors <- c('red', 'blue', 'green', 'black')
dat <- lapply(seq_along(colors), function(i){
x <- seq(1, 2*i)
data.frame(
series = colors[i],
x = x,
y = x * i + rnorm(length(x))
)}
)
dat <- do.call(rbind, dat)
Now plot
ggplot(dat, aes(x, y, color=series)) + geom_line()
这篇关于以自定义颜色,图例等方式在ggplot中绘制多个数据系列的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!