简体   繁体   English

geom_line 与 R 中 x 轴上的组

[英]geom_line with group at x axis in R

I am trying to geom_line plot such that each ID get its own line.我正在尝试geom_line绘图,以便每个ID都有自己的线条。 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 ?我怎样才能在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输出

在此处输入图片说明

Desired output期望输出

在此处输入图片说明

As highlighted in the comments, your data doesn't have an "X" variable.正如评论中突出显示的那样,您的数据没有“X”变量。 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") 

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM