【问题标题】:Adding key legend to multi-histogram plot in R将关键图例添加到 R 中的多直方图
【发布时间】:2013-01-18 23:26:54
【问题描述】:

如何在下图中添加关键图例

我希望在右上角的某处有一个关键图例,带有两个短的水平彩条,红色的应该说“整形手术出错”,蓝色的应该说“德国”。

我使用以下代码来制作情节:

bar2 <- read.table("div/ana-mut[...]/barriers-set-2.dat", sep=" ")
bar2val <- c(bar2$V1, bar2$V2)
bar3 <- read.table("div/ana-mut[...]/barriers-set-3.dat", sep=" ")
bar3val <- c(bar3$V1, bar3$V2)
p1 <- hist(subset(bar2val, bar2val < 30), breaks=30)
p2 <- hist(subset(bar3val, bar3val < 30), breaks=30)
plot(p1, col=rgb(1,0,0,8/9), main="Barrier distribution", xlab="Barrier [kcal/mol]", ylab="Mutant count")
plot(p2, col=rgb(0,0,1,8/9), add=T)

任何提示将不胜感激。

【问题讨论】:

  • 几点。首先请提出您的问题reproducible。另外,向我们展示您的尝试。

标签: r key histogram legend


【解决方案1】:

这是另一种解决方案(请参阅下面的代码)

# some semi-random data …
df <- structure(list(Germany = c(1L, 3L, 6L, 1L, 2L), Plastic = c(2L, 
5L, 4L, 2L, 3L)), .Names = c("Germany", "Plastic"), class = "data.frame", row.names = c(NA, 
-5L))

# Expand right side of clipping rect to make room for the legend
par(xpd=T, mar=par()$mar+c(0,0,0,4))

# Graph data (transposing the matrix) using heat colors,  
# put 10% of the space between each bar, and make labels  
# smaller with horizontal y-axis labels
barplot(t(df), main="Barrier distribution", xlab="Barrier [kcal/mol]", ylab="Mutant count", 
   col=c("blue", "red"), space=0.1, cex.axis=0.8, las=1,
   names.arg=c("Mon","Tue","Wed","Thu","Fri"), cex=0.8) 

# Place the legend at (4,9) using blue and red
legend(4, 9, names(df), lwd=4, col=c("blue", "red"))

# Restore default clipping rect
par(mar=c(5, 4, 4, 2) + 0.1)

【讨论】:

  • @TMOTTM,这个答案有帮助吗?
【解决方案2】:

legend 命令可以解决问题:

legend("topright", c("Germany", "Plastic"), col=c("blue", "red"), lwd=10)

要获得两个短的水平彩条,只需使用标准线,但增加线条粗细。正如 Roland 指出的,您还可以使用 fill 参数:

legend("topright", c("Germany", "Plastic"), fill=c("blue", "red"))

更多详情请见?legend

【讨论】:

  • 对于直方图,我会使用fill 参数来绘制框,而不是在图例中使用线条。
  • 感谢 csgillespie。这应该足以满足我的需求。
最近更新 更多