R语言 在ggolot2上绘制具有2种不同线型的同一条线

h43kikqp  于 2023-03-05  发布在  Go
关注(0)|答案(1)|浏览(197)

我想对线的两个部分使用两种线型:例如,虚线从黑暗到暗淡,实线从暗淡到环境。2有办法做到这一点吗?
多谢了!
下面是我目前的代码:

df <- ggplot(aes(y=Expression, x=Treatment, group=FS_Gene)) + 
  geom_line(aes(color=AM_vs_CM_Sig))

下面是我从dput获得的示例数据:

structure(list(query = c("GS1", "GS1", "GS1", "GS1", "GS1", "GS1", 
"GS1"), FS_Gene = c("FS_gene_30096", "FS_gene_30096", "FS_gene_30096", 
"FS_gene_4414", "FS_gene_4414", "FS_gene_4414", "FS_gene_58593"
), AM_vs_BM_Sig = structure(c(2L, 2L, 2L, 1L, 1L, 1L, 1L), levels = c("N", 
"Y"), class = "factor"), AM_vs_CM_Sig = structure(c(1L, 1L, 1L, 
1L, 1L, 1L, 1L), levels = c("N", "Y"), class = "factor"), BM_vs_CM_Sig = structure(c(1L, 
1L, 1L, 1L, 1L, 1L, 1L), levels = c("N", "Y"), class = "factor"), 
    Treatment = structure(c(3L, 2L, 1L, 3L, 2L, 1L, 2L), levels = c("Dark", 
    "Dim", "Ambient"), class = "factor"), Tissue = structure(c(2L, 
    2L, 2L, 2L, 2L, 2L, 2L), levels = c("Foot", "Mantle"), class = "factor"), 
    Species = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L), levels = "FS", class = "factor"), 
    Expression = c(136.7586, 197.294625, 165.17225, 4.5402, 6.27425, 
    4.406375, 2.255375)), row.names = c(NA, -7L), class = c("tbl_df", 
"tbl", "data.frame"), na.action = structure(c(`190` = 190L, `191` = 191L, 
`192` = 192L, `193` = 193L, `194` = 194L, `195` = 195L, `211` = 211L, 
`212` = 212L, `213` = 213L, `214` = 214L, `215` = 215L, `216` = 216L, 
`220` = 220L, `221` = 221L, `222` = 222L, `238` = 238L, `239` = 239L, 
`240` = 240L, `244` = 244L, `245` = 245L, `246` = 246L, `277` = 277L, 
`278` = 278L, `279` = 279L, `322` = 322L, `323` = 323L, `324` = 324L, 
`367` = 367L, `368` = 368L, `369` = 369L, `376` = 376L, `377` = 377L, 
`378` = 378L, `490` = 490L, `491` = 491L, `492` = 492L, `496` = 496L, 
`497` = 497L, `498` = 498L, `526` = 526L, `527` = 527L, `528` = 528L, 
`532` = 532L, `533` = 533L, `534` = 534L), class = "omit"))

My current result

w46czmvw

w46czmvw1#

像这样?
必须从x轴变量创建列xendyend

# test data
df1 <- iris[c(1, 51, 101), 3:5]
names(df1) <- c("N", "Y", "x")
df1
#>       N   Y          x
#> 1   1.4 0.2     setosa
#> 51  4.7 1.4 versicolor
#> 101 6.0 2.5  virginica

suppressPackageStartupMessages({
  library(ggplot2)
  library(tidyr)
  library(dplyr)
})

df1 %>%
  pivot_longer(-x) %>%
  group_by(name) %>%
  mutate(xend = lead(x),
         yend = lead(value),
         linetype = factor(row_number())) %>%
  drop_na() %>%
  ggplot(aes(x = x, y = value, color = name)) +
  geom_segment(aes(xend = xend, yend = yend, linetype = linetype))

创建于2023年3月2日,使用reprex v2.0.2

相关问题