【问题标题】:Legend for line type (or marker) and for colour in base R plot基本 R 图中线型(或标记)和颜色的图例
【发布时间】:2018-07-30 02:39:30
【问题描述】:

我有一个图表,我有几种颜色和几种线型。他们是交叉的,例如虚线是蓝色或绿色。我想要一个在 R 中使用基本图的图例,它将是一个正方形/矩形,其中行是颜色,列是线型。

更新:

在@G 的回答的帮助下。 Grothendieck,我已经了解如何获得两列,但标签仍然没有按照我想要的方式排列。使用这个answer on placing labels to the left,我想出了如何让标签出现在符号的左侧(尽管我觉得到达那里很费力而且应该更简单)。我已经使用了那个答案的存根和我在这里找到的那​​个来创建这个例子。

set.seed(1)
plot(1:10,runif(min=0,max=10,10),type='l',ylim=c(0,15),xlim=c(0,10),col=1)
lines(1:10,runif(min=0,max=10,10),col=1,lty="dashed")
lines(1:10,runif(min=0,max=10,10),col=2,lty="solid")
lines(1:10,runif(min=0,max=10,10),col=2,lty="dashed")
lines(1:10,runif(min=0,max=10,10),col=3,lty="solid")
lines(1:10,runif(min=0,max=10,10),col=3,lty="dashed")
#draw the legend lines
a <- legend(1,14,lty=rep(ltys, each = (nr)),col=1:3,legend=rep("",6),bty="n", ncol=nc,
        trace=TRUE)
#place text labels one value to the left of the legend lines for only the first column
text(a$text$x[1:3]-1,a$text$y[1:3],Vars,pos=2)
#place a text label above the legend lines for the second attribute to define in legend
text(a$text$x[c(1,4)]-1.5, 14, c("Young", "Old"), pos=4)

有没有更简单的东西,或者这是 R 能给我的最好的东西?

【问题讨论】:

  • 如果您感到绝望,您可以随时使用textsegments 自己创建图例。

标签: r plot legend


【解决方案1】:

1) 这里第一行是黑色,第二行是红色,第三行是绿色。第一列是实线,第二列是虚线。我们使用 title= 来提供列的标题。这将需要一些试验和错误才能获得正确的定位。请参阅 (2) 了解替代方案。

nc <- 2   
Vars <- c("VarA", "VarB", "VarC")
nr <- length(Vars)

plot(0)
legend("topleft", rep(Vars, nc), col = 1:nr, 
   lty = rep(1:nc, each = nr), ncol = nc, cex = 0.8, 
   title = "        Young              Old")

2) 类似,但我们添加了一行不带行的行作为标题,避免了 title 方法的繁琐试验和错误。

nc <- 2   
Vars <- c("VarA", "VarB", "VarC")
nr <- length(Vars)

plot(0)
legend("topleft", c("Young", Vars, "Old", Vars), col = 0:nr, 
   lty = 0:nr, ncol = nc, cex = 0.8)

【讨论】:

  • 我可以得到它,以便在实线上方有一个标签(“mean”)和另一个在虚线(“sd”)上方?
  • 为列标题添加了两种方法。
猜你喜欢
  • 1970-01-01
  • 2013-06-14
  • 1970-01-01
  • 2014-10-24
  • 2018-07-31
  • 2022-08-19
  • 2011-09-25
  • 2019-11-12
  • 1970-01-01
相关资源
最近更新 更多