【问题标题】:Is there a way to plot most columns of a matrix as one color, but specify several columns to be plotted in unique colors?有没有办法将矩阵的大多数列绘制为一种颜色,但指定几列以独特的颜色绘制?
【发布时间】:2020-11-28 20:24:16
【问题描述】:

我正在使用一个名为 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

包含以行年份中的列字母开头的名字的百分比,对于所有字母 A-Z 和年份 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))

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

【问题讨论】:

    标签: r matrix plot


    【解决方案1】:

    您可以多次拨打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))
    

    关键:

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

    【讨论】:

    • 我并不急于让这个“接受”,但既然你是新来的:当有答案时,这里的礼仪是accept the best answer;这样做不仅为回答者提供了一些积分,而且还为有类似问题的读者提供了一些关闭。尽管您只能接受一个答案,但您可以选择对您认为有帮助的人进行投票。再说一次,不要着急:一个常见的策略是让它在“一段时间”内无人回答(以防建议更好的方法),所以不要着急,但请务必回来。谢谢!
    • 嘿,对不起。刚刚接受了你的回答(我很确定)。感谢您的建议和代码帮助!
    猜你喜欢
    • 2011-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多