0

阿罗哈——

我正在创建一系列直方图,并希望添加一条表示分布平均值的垂直线以及一个表示样本大小的文本标签。我的代码如下:

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.ablineandpanel.text函数来完成panel.histogram,但这似乎不起作用。我究竟做错了什么?如果有人能给我一个虚拟垂直线(例如 x=10)和虚拟文本的代码,我可以很容易地插入平均值和样本大小的方程。

4

1 回答 1

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))
}

...生成图形:

在此处输入图像描述

于 2013-05-21T05:18:04.810 回答