简体   繁体   English

ggplot2 中的绘图线

[英]Plotting lines in ggplot2

Is it possible to make this graph with ggplot, ordering the graph by the variable "t" in ascending order, distinguishing each "t" according to status (black or white circle, it can be another marker...) and if possible the variable "id " on the ordinate axis.是否可以使用ggplot制作此图,按变量“t”以升序对图进行排序,根据状态区分每个“t”(黑色或白色圆圈,它可以是另一个标记......),如果可能的话纵坐标轴上的变量“id”。

Id<- c(1,2,3,4)
t<- c(10,5,20,15)
status<- c(0,1,0,1)
df<- data.frame(Id, t, status)

在此处输入图像描述

Maybe you want something like this using geom_segment for the lines with geom_vline for the vertical lines.也许你想要这样的东西,使用geom_segmentgeom_vline作为垂直线。 Using shape and fill aesthetics to fill the points with "black" and "white" per status.使用shapefill美学来填充每个状态的“黑色”和“白色”点。 You can use the following code:您可以使用以下代码:

Id<- c(1,2,3,4)
t<- c(10,5,20,15)
status<- c(0,1,0,1)
df<- data.frame(Id, t, status)

library(ggplot2)
library(dplyr)
library(forcats)
df %>%
  mutate(Id = as.factor(Id),
         status = as.factor(status)) %>%
  ggplot(aes(x = t, y = fct_reorder(Id, t, .desc = TRUE), shape = status, fill = status)) +
  geom_point() +
  geom_segment(aes(x = 0, xend = t, y = Id, yend = Id)) +
  geom_vline(xintercept=c(t),linetype="dotted", alpha = 0.4) +
  scale_shape_manual(values=c(21, 21), name = "shapes!") +
  scale_fill_manual(values=c("black", "white")) +
  scale_x_continuous(expand = c(0, 0), limits = c(0, 25)) + 
  labs(x = "", y = "Id") +
  theme_bw() +
  theme(panel.grid.major = element_blank(), 
        panel.grid.minor = element_blank(),
        legend.position = "none",
        axis.title.y = element_text(angle=0)) 

Created on 2022-07-25 by the reprex package (v2.0.1)代表 package (v2.0.1) 于 2022 年 7 月 25 日创建

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

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