阿罗哈 -
我正在创建一系列直方图,并希望添加一条垂直线,指示分布的平均值以及指示样本大小的文本标签。我的代码如下:
BIN_WIDTH <- 1 #desired bin width
print(histogram(~ Length..cm. | Method, #create and print the histogram and save to variable "graph"
data = hist.data[hist.data$Scientific_name == "Pristipomoides filamentosus",],
nint = (max(hist.data$Length..cm.) - min(hist.data$Length..cm.)+1)/BIN_WIDTH,
layout = c(1,2),
type = "density",
main = "Length-Frequency of Pristipomoides filamentosus by Gear",
xlab = "Length (cm)",
panel = function(x, ...){
panel.histogram(x,...)
panel.mathdensity(dmath = dnorm, col = "red",
args = list(mean = mean(x), sd= sd(x)), ...)
}
))
我认为这可以使用panel.abline
之后插入的panel.text
和panel.histogram
函数来完成,但这似乎不起作用。我究竟做错了什么?如果有人可以给我一个虚拟垂直线(例如x = 10)和虚拟文本的代码,我可以很容易地插入平均值和样本大小的等式。
答案 0 :(得分:0)
您需要panel.lines()
和panel.text()
。例如,以下函数在条形图上放置一条水平线,并用文本注释它,以及放入一个自定义的图例:
function () {
trellis.device(width = 5, height = 5, new = F)
xx <- GERD95.06
xx$Country <- c("USA", "Singapore", "Denmark", "Australia",
"NZ")
barchart(X1995 + X2006 ~ reorder(Country, xx$X2006), data = xx,
ylab = "GERD per capita, nominal $US PPP", cex = 0.8,
panel = function(...) {
panel.lines(c(0.7, 5), c(720, 720), col = "gray",
lwd = 4)
panel.text(lab = "OECD avg 2006", x = 1, y = 750,
adj = c(0.4, 0), cex = 0.7)
panel.text(lab = "NZ at 2.5% of GDP", x = 1, y = 630,
adj = c(0.4, 0), cex = 0.7)
panel.text(lab = "1995", x = 1.5, y = 900, adj = c(1,
0.5))
panel.rect(xleft = 1.6, xright = 2, ybottom = 870,
ytop = 930, col = 3)
panel.text(lab = "2006", x = 1.5, y = 1000, adj = c(1,
0.5))
panel.rect(xleft = 1.6, xright = 2, ybottom = 970,
ytop = 1030, col = 8)
panel.barchart(..., col = c(3, 8))
panel.rect(xleft = 1, xright = 1.3333, ybottom = xx$X2006[xx$Country ==
"NZ"], ytop = 2.5/1.206 * xx$X2006[xx$Country ==
"NZ"])
}, ylim = c(0, 1200))
}
...生成图表: