-1

I am trying to geom_line plot such that each ID get its own line. However, the current produces vertical lines instead of horizontal lines.

I already looked here and here and here for help but still can't figure out what I am doing wrong.

How can I fix this in R?

Sample data and code

ID = c("279557", "279557","279557", "279557", "280485", "280485", "280485", "280485") Var1 = c("1000", "1500", "2000", "3000", "1100", "1700", "2900", "3500") Var2 = c("3500", "4800", "5500", "6800", "3800", "5800", "6500", "7800") library(tidyverse) df = data.frame(ID, Var1, Var2) df= df%>% pivot_longer(-c(ID)) df %>% ggplot(aes(x = ID, y = value, group = ID)) + geom_line(size = 1) + labs(x = "ID",y = "value") 

Output

enter image description here

Desired output

enter image description here

4
  • what variable is on the x axis on your plot? Commented Nov 14, 2021 at 11:22
  • The variable on x-axis is ID. Commented Nov 14, 2021 at 11:23
  • 1
    ... I am afraid that does not make any sense ... You need a different x variable, for example time. Commented Nov 14, 2021 at 11:26
  • 1
    Thank you. But in your line drawing, how far apart do you want each point to be? That would typically be the x variable. You need both and x and y coordinate. since there are only 2 x coordinates (279557 and 280485), all the points are in a straight vertical line Commented Nov 14, 2021 at 11:26

1 Answer 1

1

As highlighted in the comments, your data doesn't have an "X" variable. This would typically be something like time or location. Alternatively, manually add one based on the grouped row number. To add the legend, include a mappable value like colour in the aesthetics.

df = df %>% pivot_longer(-c(ID)) %>% group_by(ID) %>% mutate(row = row_number()) df %>% ggplot(aes(x = row, y = value, group = ID, colour = ID)) + geom_line(size = 1) + labs(x = "ID",y = "value") 

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.