绘制多行(数据系列),每一行都有独特的颜色。

时间:2022-09-15 09:30:57

I am fairly new to R and I have the following queries :

我对R相当陌生,我有以下几个问题:

I am trying to generate a plot in R which has multiple lines (data series). Each of these lines is a category and I want it to have a unique color.

我正在尝试在R中生成一个有多行(数据系列)的图。每一行都是一个类别,我希望它有一个独特的颜色。

Currently my code is setup in this way :

目前我的代码是这样设置的:

First, I am creating an empty plot :

首先,我创作了一个空洞的情节:

plot(1,type='n',xlim=c(1,10),ylim=c(0,max_y),xlab='ID', ylab='Frequency')

Then for each of my category, I am plotting lines in this empty plot using a "for" loop like so :

然后对于我的每一个类别,我在这个空的图中画线,用一个“for”循环来表示:

for (category in categories){
lines(data.frame.for.this.category, type='o', col=sample(rainbow(10)), lwd=2)
}

There are 8 categories here, and so there are 8 lines produced in the plot. As you can see, I am trying to sample a color from the rainbows() function to generate a color for each line.

这里有8个类别,所以在这个情节中有8行。如您所见,我正在尝试从rainbows()函数中提取颜色,为每一行生成一个颜色。

However, when the plot is generated, I find that there are multiple lines which have the same color. For instance, 3 of those 8 lines have green color.

然而,当这个图生成时,我发现有很多线都有相同的颜色。例如,这8行中有3行是绿色的。

How do I make each of these 8 lines have a unique color ?

我如何让这8条线的每一条都有一个独特的颜色?

Also, how do I reflect this uniqueness in the legend of the plot ? I was trying to lookup the legend() function, however it was not clear which parameter I should use to reflect this unique color for each category ?

另外,我如何在故事的传说中反映这种独特性呢?我试图查找legend()函数,但是不清楚应该用哪个参数来反映每个类别的唯一颜色?

Any help or suggestions would be much appreciated.

如有任何帮助或建议,将不胜感激。

8 个解决方案

#1


60  

If your data is in wide format matplot is made for this and often forgotten about:

如果你的数据是宽格式的,matplot是为这个而做的,并且经常被遗忘:

 dat <- matrix(runif(40,1,20),ncol=4) # make data
 matplot(dat, type = c("b"),pch=1,col = 1:4) #plot
 legend("topleft", legend = 1:4, col=1:4, pch=1) # optional legend

There is also the added bonus for those unfamiliar with things like ggplot that most of the plotting paramters such as pch etc. are the same using matplot() as plot(). 绘制多行(数据系列),每一行都有独特的颜色。

对于那些不熟悉像ggplot这样的东西的人来说,也有额外的好处,比如像pch之类的绘图工具,使用matplot()和plot()是一样的。

#2


43  

If you would like a ggplot2 solution, you can do this if you can shape your data to this format (see example below)

如果您想要一个ggplot2解决方案,您可以这样做,如果您可以将您的数据塑造成这种格式(参见下面的示例)

# dummy data
set.seed(45)
df <- data.frame(x=rep(1:5, 9), val=sample(1:100, 45), 
                   variable=rep(paste0("category", 1:9), each=5))
# plot
ggplot(data = df, aes(x=x, y=val)) + geom_line(aes(colour=variable))

绘制多行(数据系列),每一行都有独特的颜色。

#3


22  

You have the right general strategy for doing this using base graphics, but as was pointed out you're essentially telling R to pick a random color from a set of 10 for each line. Given that, it's not surprising that you will occasionally get two lines with the same color. Here's an example using base graphics:

你有正确的使用基本图形的一般策略,但正如你指出的,你实际上是在告诉R从每行10中选取一个随机的颜色。考虑到这一点,你偶尔会得到两行同样的颜色也就不足为奇了。下面是一个使用基本图形的例子:

plot(0,0,xlim = c(-10,10),ylim = c(-10,10),type = "n")

cl <- rainbow(5)

for (i in 1:5){
    lines(-10:10,runif(21,-10,10),col = cl[i],type = 'b')
}

绘制多行(数据系列),每一行都有独特的颜色。

Note the use of type = "n" to suppress all plotting in the original call to set up the window, and the indexing of cl inside the for loop.

注意,type = "n"的使用可以抑制原始调用中设置窗口的所有绘图,并在for循环中对cl进行索引。

#4


7  

Using @Arun dummy data :) here a lattice solution :

使用@Arun虚拟数据:)这里有一个点阵解决方案:

xyplot(val~x,type=c('l','p'),groups= variable,data=df,auto.key=T)

绘制多行(数据系列),每一行都有独特的颜色。

#5


3  

More than one line can be drawn on the same chart by using the lines()function

通过使用lines()函数可以在同一个图表上绘制多个行。

# Create the data for the chart.
v <- c(7,12,28,3,41)
t <- c(14,7,6,19,3)

# Give the chart file a name.
png(file = "line_chart_2_lines.jpg")

# Plot the bar chart.
plot(v,type = "o",col = "red", xlab = "Month", ylab = "Rain fall", 
   main = "Rain fall chart")

lines(t, type = "o", col = "blue")

# Save the file.
dev.off()

OUTPUT 绘制多行(数据系列),每一行都有独特的颜色。

输出

#6


2  

Here are nice description how to add lines to

这里有很好的说明如何添加行。

plot()

图()

using function -

使用函数,

par(new=T)

par(新= T)

option

选项

http://cran.r-project.org/doc/contrib/Lemon-kickstart/kr_addat.html

http://cran.r-project.org/doc/contrib/Lemon-kickstart/kr_addat.html

To color them differently you will need

你需要用不同的颜色来给它们着色。

col()

坳()

option. To avoid superfluous axes descriptions use

选择。为了避免多余的轴描述使用。

xaxt="n"

xaxt = " n "

and

yaxt="n"

yaxt = " n "

for second and further plots.

为第二和更多的情节。

#7


2  

I know, its old a post to answer but like I came across searching for the same post, someone else might turn here as well

我知道,它的旧帖子可以回答,但就像我在同一篇文章中寻找的一样,其他人也可能会在这里转。

By adding : colour in ggplot function , I could achieve the lines with different colors related to the group present in the plot.

通过添加:ggplot函数中的颜色,我可以得到与图中所示的组相关的不同颜色的线条。

ggplot(data=Set6, aes(x=Semana, y=Net_Sales_in_pesos, group = Agencia_ID, colour = as.factor(Agencia_ID)))    

and

geom_line() 

绘制多行(数据系列),每一行都有独特的颜色。

#8


1  

Here is a sample code that includes a legend if that is of interest.

下面是一个示例代码,其中包含一个关于感兴趣的图例。

# First create an empty plot.
plot(1, type = 'n', xlim = c(xminp, xmaxp), ylim = c(0, 1), 
     xlab = "log transformed coverage", ylab = "frequency")

# Create a list of 22 colors to use for the lines.
cl <- rainbow(22)

# Now fill plot with the log transformed coverage data from the
# files one by one.
for(i in 1:length(data)) {
    lines(density(log(data[[i]]$coverage)), col = cl[i])
    plotcol[i] <- cl[i]
}
legend("topright", legend = c(list.files()), col = plotcol, lwd = 1,
       cex = 0.5)

#1


60  

If your data is in wide format matplot is made for this and often forgotten about:

如果你的数据是宽格式的,matplot是为这个而做的,并且经常被遗忘:

 dat <- matrix(runif(40,1,20),ncol=4) # make data
 matplot(dat, type = c("b"),pch=1,col = 1:4) #plot
 legend("topleft", legend = 1:4, col=1:4, pch=1) # optional legend

There is also the added bonus for those unfamiliar with things like ggplot that most of the plotting paramters such as pch etc. are the same using matplot() as plot(). 绘制多行(数据系列),每一行都有独特的颜色。

对于那些不熟悉像ggplot这样的东西的人来说,也有额外的好处,比如像pch之类的绘图工具,使用matplot()和plot()是一样的。

#2


43  

If you would like a ggplot2 solution, you can do this if you can shape your data to this format (see example below)

如果您想要一个ggplot2解决方案,您可以这样做,如果您可以将您的数据塑造成这种格式(参见下面的示例)

# dummy data
set.seed(45)
df <- data.frame(x=rep(1:5, 9), val=sample(1:100, 45), 
                   variable=rep(paste0("category", 1:9), each=5))
# plot
ggplot(data = df, aes(x=x, y=val)) + geom_line(aes(colour=variable))

绘制多行(数据系列),每一行都有独特的颜色。

#3


22  

You have the right general strategy for doing this using base graphics, but as was pointed out you're essentially telling R to pick a random color from a set of 10 for each line. Given that, it's not surprising that you will occasionally get two lines with the same color. Here's an example using base graphics:

你有正确的使用基本图形的一般策略,但正如你指出的,你实际上是在告诉R从每行10中选取一个随机的颜色。考虑到这一点,你偶尔会得到两行同样的颜色也就不足为奇了。下面是一个使用基本图形的例子:

plot(0,0,xlim = c(-10,10),ylim = c(-10,10),type = "n")

cl <- rainbow(5)

for (i in 1:5){
    lines(-10:10,runif(21,-10,10),col = cl[i],type = 'b')
}

绘制多行(数据系列),每一行都有独特的颜色。

Note the use of type = "n" to suppress all plotting in the original call to set up the window, and the indexing of cl inside the for loop.

注意,type = "n"的使用可以抑制原始调用中设置窗口的所有绘图,并在for循环中对cl进行索引。

#4


7  

Using @Arun dummy data :) here a lattice solution :

使用@Arun虚拟数据:)这里有一个点阵解决方案:

xyplot(val~x,type=c('l','p'),groups= variable,data=df,auto.key=T)

绘制多行(数据系列),每一行都有独特的颜色。

#5


3  

More than one line can be drawn on the same chart by using the lines()function

通过使用lines()函数可以在同一个图表上绘制多个行。

# Create the data for the chart.
v <- c(7,12,28,3,41)
t <- c(14,7,6,19,3)

# Give the chart file a name.
png(file = "line_chart_2_lines.jpg")

# Plot the bar chart.
plot(v,type = "o",col = "red", xlab = "Month", ylab = "Rain fall", 
   main = "Rain fall chart")

lines(t, type = "o", col = "blue")

# Save the file.
dev.off()

OUTPUT 绘制多行(数据系列),每一行都有独特的颜色。

输出

#6


2  

Here are nice description how to add lines to

这里有很好的说明如何添加行。

plot()

图()

using function -

使用函数,

par(new=T)

par(新= T)

option

选项

http://cran.r-project.org/doc/contrib/Lemon-kickstart/kr_addat.html

http://cran.r-project.org/doc/contrib/Lemon-kickstart/kr_addat.html

To color them differently you will need

你需要用不同的颜色来给它们着色。

col()

坳()

option. To avoid superfluous axes descriptions use

选择。为了避免多余的轴描述使用。

xaxt="n"

xaxt = " n "

and

yaxt="n"

yaxt = " n "

for second and further plots.

为第二和更多的情节。

#7


2  

I know, its old a post to answer but like I came across searching for the same post, someone else might turn here as well

我知道,它的旧帖子可以回答,但就像我在同一篇文章中寻找的一样,其他人也可能会在这里转。

By adding : colour in ggplot function , I could achieve the lines with different colors related to the group present in the plot.

通过添加:ggplot函数中的颜色,我可以得到与图中所示的组相关的不同颜色的线条。

ggplot(data=Set6, aes(x=Semana, y=Net_Sales_in_pesos, group = Agencia_ID, colour = as.factor(Agencia_ID)))    

and

geom_line() 

绘制多行(数据系列),每一行都有独特的颜色。

#8


1  

Here is a sample code that includes a legend if that is of interest.

下面是一个示例代码,其中包含一个关于感兴趣的图例。

# First create an empty plot.
plot(1, type = 'n', xlim = c(xminp, xmaxp), ylim = c(0, 1), 
     xlab = "log transformed coverage", ylab = "frequency")

# Create a list of 22 colors to use for the lines.
cl <- rainbow(22)

# Now fill plot with the log transformed coverage data from the
# files one by one.
for(i in 1:length(data)) {
    lines(density(log(data[[i]]$coverage)), col = cl[i])
    plotcol[i] <- cl[i]
}
legend("topright", legend = c(list.files()), col = plotcol, lwd = 1,
       cex = 0.5)