标记图中的特定点

时间:2018-11-23 14:08:21

标签: r plot label

这里有两个向量:“ Pr”和“ Z”

这是我的代码:

Z=seq(1,10,by=0.5)
Pr=lapply(Z,functionZ)

plot(Z,Pr,main="CAT Bond Price with increasing attachment points",xlab="Attachment Point",ylab="Price")
 grid(nx = NULL, ny = NULL, col = "blue", lty = "dotted")

我只想在图中选择 两个点,即Z = 5和Z = 7.5的两个点,并将它们分别标记为“ A类”和“ B类”。我该怎么办?

2 个答案:

答案 0 :(得分:1)

您的示例不可复制,因此我制作了一些随机数据并使用ggplot进行了绘制:

  Z=seq(1,10,by=0.5)
  Pr <- 1:19
  L <- c("Point1", rep(NA, 17), "Point19")
  df <- data.frame(Pr, Z, L)

  library(ggplot2)
  ggplot(aes(x=Pr, y=Z, label=L), data=df) +
    geom_point() +
    geom_label() +
    xlab("Attachment Point") +
    ylab("Price") +
    ggtitle("CAT Bond Price with increasing attachment points") +
    theme_classic()

您只需在一个单独的标签列中定义要显示标签的标签,其余步骤由ggplot进行。

在您的情况下,当您定义L时,只需

 L <- ifelse(Z==7, "Class A", ifelse(Z==7.5, "Class B", NA))

答案 1 :(得分:1)

要坚持使用基本R绘图,可以使用text函数。

由于您没有提供您的FunctionZ,因此我仅举一些例子。我将标签放置在这些点的左侧。根据函数的形状,您可能希望调整pos参数以将其放置在其他位置。

Z=seq(1,10,by=0.5)
functionZ = function(x) x + sin(x)
Pr=lapply(Z,functionZ)

plot(Z,Pr,main="CAT Bond Price with increasing attachment points",
    xlab="Attachment Point",ylab="Price")
grid(nx = NULL, ny = NULL, col = "blue", lty = "dotted")

text(x=c(5,7.5), y=functionZ(c(5,7.5)), labels= c("Class A", "Class B"), pos=2)

Labeled Plot