在R中绘制多条具有唯一颜色的线(数据系列) [英] Plot multiple lines (data series) each with unique color in R
问题描述
我对R相当新,我有以下查询:
我试图在R中生成一个有多行(数据系列)的图。每一行都是一个类别,我想让它有一个独特的颜色。
目前我的代码是这样设置的:
首先,我创建一个空图: p>
plot(1,type ='n',xlim = c(1,10),ylim = c(0,max_y) xlab ='ID',ylab ='Frequency')
使用for循环在这个空图中绘制线条,如下所示:
lines(data.frame.for.this.category,type ='o',col = sample(rainbow(10)),lwd = 2)
pre>
}
这里有8个类别,所以在绘图中有8行。正如你所看到的,我试图从rainbows()函数中抽取一个颜色,为每一行生成一个颜色。
但是,当绘制图时,我发现有多条具有相同颜色的线。例如,这8行中的3行具有绿色。
如何使这8行中的每一行具有独特的颜色?
此外,如何在图表的图例中反映这个唯一性?我试图查找
legend()
函数,但是不清楚应该使用哪个参数来反映每个类别的这种独特的颜色?
任何帮助或建议都将非常感激。
谢谢。
解决方案如果您的数据位于宽格式
matplot
是为此而编写,常常忘记:dat
matplot(dat,type = c(b pch = 1,col = 1:4)#plot
legend(topleft,legend = 1:4,col = 1:4,pch = 1)#可选图例
对于不熟悉
ggplot
的人来说,使用matplot()
作为plot()来绘制诸如
。pch
>I am fairly new to R and I have the following queries :
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')
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) }
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.
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.
How do I make each of these 8 lines have a unique color ?
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.
Thanks.
解决方案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
There is also the added bonus for those unfamiliar with things like
ggplot
that most of the plotting paramters such aspch
etc. are the same usingmatplot()
asplot()
.这篇关于在R中绘制多条具有唯一颜色的线(数据系列)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!