首页 > 解决方案 > 有没有办法将矩阵的大多数列绘制为一种颜色,但指定几列以独特的颜色绘制?

问题描述

我正在使用一个名为 percs 的矩阵

            A        B        C
1931 6.193944 8.978485 4.725187
1932 6.111085 9.266212 4.971554
1933 6.004230 9.300532 5.350349
1934 5.849529 9.285559 5.660330
1935 5.702953 8.996875 5.769253

对于所有字母 AZ 和 1931-2010 年,包含以行年份中的列字母开头的名字的百分比。我使用以下代码将每列绘制在一起

plot.new()
par(mar=c(5,7,5,3))
matplot(percs, type="l",
        main = "Occurence of First Letters of Names in Females, 1931-2010",
        xlab = "Year",
        ylab = "",
        cex.axis=0.8,
        cex.lab=1.1,
        las=1,
        xaxt="n",
        col="gray")
mtext("Percent of \n All Names", side = 2, line = 2, las =1, cex=1.1)
axis(1, at=seq(1, 80, 10), labels=seq(1931, 2010, 10))

我想以灰色绘制大多数字母,然后指定三个字母以黑色绘制并标记,以便查看者可以看到哪些字母突出。有谁知道如何指定哪些列被着色和标记?谢谢!

标签: rmatrixplot

解决方案


您可以多次调用matplot.

par(mar=c(5,7,5,3))
grays <- c(1,3)
reds <- c(2)
matplot(percs[,grays,drop=FALSE], # updated, subsetting
        type="l",
        main = "Occurence of First Letters of Names in Females, 1931-2010",
        xlab = "Year",
        ylab = "",
        cex.axis=0.8,
        cex.lab=1.1,
        las=1,
        xaxt="n",
        ylim = range(percs),      # NEW
        col="gray")
matplot(percs[,reds,drop=FALSE], type="l", col="red", add=TRUE) # additional call
mtext("Percent of \n All Names", side = 2, line = 2, las =1, cex=1.1)
axis(1, at=seq(1, 80, 10), labels=seq(1931, 2010, 10))

带有红/灰线的多个matplots

钥匙:

  • 第一次调用matplot应该设置ylim=range(percs),否则可能要添加的列将在绘图区域之外;
  • 随后的调用只matplot需要数据、the type=、newcol=add=TRUE; 和
  • drop=FALSE在只选择​​一列的情况下,使用是防御性的。

推荐阅读