在 R 中绘制多条线(数据系列),每条线都具有独特的颜色
我是 R 的新手,我有以下疑问:
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.
目前我的代码是这样设置的:
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')
然后对于我的每个类别,我使用for"循环在这个空图中绘制线条,如下所示:
Then for each of my category, I am plotting lines in this empty plot using a "for" loop like so :
for (category in categories){
lines(data.frame.for.this.category, type='o', col=sample(rainbow(10)), lwd=2)
}
这里有 8 个类别,因此图中产生了 8 条线.如您所见,我正在尝试从 Rainbows() 函数中采样一种颜色,以便为每条线生成一种颜色.
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 条线中有 3 条是绿色的.
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 条线中的每一条都具有独特的颜色?
How do I make each of these 8 lines have a unique color ?
另外,我如何在情节的传说中体现这种独特性?我试图查找 legend()
函数,但是不清楚我应该使用哪个参数来反映每个类别的这种独特颜色?
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 ?
任何帮助或建议将不胜感激.
Any help or suggestions would be much appreciated.
如果您的数据位于 wideformat matplot
就是为此而设计的,但经常被遗忘:
If your data is in wide format matplot
is made for this and often forgotten about:
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
对于那些不熟悉诸如 ggplot
之类的东西的人来说,还有一个额外的好处,即大多数绘图参数,例如 pch
等,使用 matplot()
作为 plot()
.
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()
.