1

I am trying to plot two scatter lines in ggplot. The x axis is integers from 1 to 10. Initially I wrote the following code:

library(ggplot2)
Answer <- c(1:10)
EM = c(0.458,0.517,0.4,0.394,0.15,0.15,0.0,0.2,0.14,0.33)
F1 = c( 0.56,0.63,0.632,0.704,0.502,0.524,0.488,0.64,0.5,0.593)
test_data <- data.frame(EM,F1,Answer)

ggplot(test_data, aes(Answer)) + 
  geom_line(aes(y = EM, colour = "EM")) + 
  geom_line(aes(y = F1, colour = "F1"))

This results in the following plot

enter image description here

The x axis is continuous here and printing values like 2.5,7.5. To make it factor ie 1,2,3,4,...,10 I tried putting aes(factor(Answer)) but this results in empty plot. How can I fix this?

hi15
  • 2,113
  • 6
  • 28
  • 51
  • 2
    In addition to the answers below, you may consider to reshape your data to long format, i.e., one column for all `y` values and a second column for the variables (`EM`, `F1`) which is preferred for efficiently working with `ggplot2`. This would also solve the issue that your y-axis is labelled `EM` now, although you show values of two variables. – Uwe Mar 21 '17 at 08:55

1 Answers1

4

Keep your data continuous. If you want to change the scale, do just that:

ggplot(test_data, aes(Answer)) + 
  geom_line(aes(y = EM, colour = "EM")) + 
  geom_line(aes(y = F1, colour = "F1")) +
  scale_x_continuous(breaks = 1:10)

resulting plot

Roland
  • 127,288
  • 10
  • 191
  • 288