在ggplot中标记特定点

时间:2019-06-26 09:39:02

标签: r ggplot2

我希望通过ggplot创建的某些点在图形的侧面带有标签,但是我无法通过当前代码来实现。

Ceplane1是具有两列和100行的矩阵(可以采用任何随机数)。我想在column 2上绘制x-axis,在column 1上绘制y-axis。我已经使用以下代码完成了这一部分。现在,我想对代码进行更改,以便可以将标签放在图形的侧面而不是图形区域本身。另外,我想用逗号表示轴。您可以将result.table[1,1]result.table[1,3]设为某个数字并提出解决方案。

ggplot(Ceplane1, aes(x = Ceplane1[,2], y = Ceplane1[,1])) +
  geom_point(colour="blue")+geom_abline(slope = -results.table[5,1],intercept = 0,colour="darkred",size=1.25)+
  geom_point(aes(mean(Ceplane1[,2]),mean(Ceplane1[,1])),colour="red")+
  geom_point(aes(results.table[1,1],results.table[3,1],colour="darkred"))+ggtitle("CE-Plane: Drug A vs Drug P")+
  xlab("QALY Difference")+ylab("Cost Difference")+xlim(-0.05,0.05)+ylim(-6000,6000)+
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
        panel.background = element_blank(),plot.background = element_rect(fill = "white", colour = "black", size = 0.5))+
  geom_vline(xintercept = 0,colour="black")+geom_hline(yintercept = 0,colour="black")+
  geom_label(aes(mean(Ceplane1[,2]),mean(Ceplane1[,1])),label="mean")+
  geom_label(aes(results.table[1,1],results.table[3,1]),label="Base ICER")

我想将标签放在图形的侧面,而不是图形本身的点上。请给我建议一种方法。

1 个答案:

答案 0 :(得分:1)

我认为最好的方法是将meanBase ICER点添加到数据集中。然后为legend添加一列,您会看到它们在图表和图例中显示为匹配:

library(ggplot2)

set.seed(1)
Ceplane1 <- data.frame(y = rnorm(100), 
                  x = rnorm(100))
results.table <- data.frame(z = rnorm(100))
Ceplane1$Legend <- "Data"

meanPoint <- data.frame(y = mean(Ceplane1[,1]), x = mean(Ceplane1[,2]), Legend = "Mean")
basePoint <- data.frame(y = results.table[3,1], x = results.table[1,1], Legend = "Base ICER")

Ceplane1 <- rbind(Ceplane1, meanPoint)
Ceplane1 <- rbind(Ceplane1, basePoint)

ggplot(Ceplane1, aes(x = x, y = y, color = Legend)) +
  geom_point() +
  geom_abline(slope = -results.table[5,1],intercept = 0,colour="darkred",size=1.25) +
  ggtitle("CE-Plane: Drug A vs Drug P")+ xlab("QALY Difference")+ylab("Cost Difference") +
  xlim(-3,3) + ylim(-3,3) + 
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), 
        panel.background = element_blank(),plot.background = element_rect(fill = "white", colour = "black", size = 0.5)) +
  geom_vline(xintercept = 0,colour="black") +
  geom_hline(yintercept = 0,colour="black")

这给了我以下内容:

enter image description here

请注意,我更改了xlim和ylim以匹配我创建的随机数据。