-2

I need to add value labels for data points on two separate lines that are generated from a data frame in R using ggplot2. The following is the code snippet that I am using:

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) 

However, the graph is only displaying the labels on the second line, i.e. the one corresponding to the Legend "Revenue as % of cost". How can I generate labels for data points on all lines generated from the same data frame in ggplot2?

Usman Khaliq
  • 363
  • 3
  • 22
  • 4
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. Right now we can't see what you are looking at. – MrFlick May 17 '19 at 22:22

1 Answers1

-1

I am not able to reproduce your example. Can you please use this dataset to reproduce your problem or draw on it what you would like to change?

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

yake84
  • 3,004
  • 2
  • 19
  • 35
  • Since the OP included neither sample data nor output, it would be hard to put together a solid answer. How does this differ substantially from their code, aside from including `hjust`? – camille May 18 '19 at 01:25
  • The comment said only labels we're showing for one line. I can't replicate the issue. I would recommend they post a picture of the desired output so we can help. – yake84 May 18 '19 at 01:28