将值标签添加到从一个数据框生成的两条线的点上

时间:2019-05-17 22:15:14

标签: r ggplot2

我需要为两个单独的行上的数据点添加值标签,这是使用ggplot2从R中的数据帧生成的。以下是我正在使用的代码段:

DataFrame = data.frame(Amount = c(results$Costs,
                                      results$TotalPoC),
                           Legend = rep(c("Cost as % of initial costs",
                                          "Revenue as % of cost"),
                                        each = nrow(results)),
                           Year = rep(0:5,2)) 
    p <- ggplot(ResultsCR, aes(x=Year, y=Amount, group=Legend)) +
      geom_line(aes(linetype=Legend))+
      geom_point(aes(shape=Legend))+
      geom_text(aes(label=Amount))+
      theme_classic(base_size = 15) +
      ggtitle("Hospital Costs and Revenues")
    print(p) 

但是,该图形仅在第二行显示标签,即与图例“收入占成本百分比”相对应的标签。如何在ggplot2中从同一数据帧生成的所有行上的数据点生成标签?

1 个答案:

答案 0 :(得分:-1)

我无法复制您的示例。您能否使用此数据集重现您的问题或利用您要更改的内容?

library(tidyverse)

set.seed(1)
df <-
  tibble(
    amount = sample(10:30, 10),
    legend = rep(
      c("Cost as % of initial costs",
        "Revenue as % of cost"),
      each = 5),
    year = rep(1:5, 2)
  )

ggplot(df, aes(x = year, y = amount, group = legend)) +
  geom_line(aes(linetype = legend)) +
  geom_point(aes(shape = legend)) +
  geom_text(aes(label = amount), hjust = -1) +
  theme_classic(base_size = 15) +
  xlim(1, 5.5) +
  ggtitle("Hospital Costs and Revenues")

enter image description here