首页 > 解决方案 > 用 R 绘制事件序列数据图表

问题描述

我是 R 的图表工具的新手,我有一个任务,我怀疑使用 R 可以轻松完成。我使用以下脚本制作了事件序列的阶梯线图:

p = ggplot(data=NULL, aes(stepStartTime, index, group=robot, color=effStatus))+
  geom_step(data=robots)+
  scale_y_reverse(lim=c(65,2))+ 
   theme(
     legend.position="none",
     axis.ticks = element_blank(), 
     axis.text.x = element_blank(), 
     axis.text.y = element_blank(), 
     axis.title.x = element_blank(), 
     axis.title.y = element_blank(),
     panel.background = element_rect(fill = 'transparent', colour = NA),
     plot.background = element_rect(fill = 'transparent', colour = NA)
 )
p + scale_color_manual(values=c("#00ff00", "#0080ff", "#ff0000" )) 

结果是这样的:

.

我希望它显示的是每个事件作为图表上的一个谨慎点,就像这样。X 轴是时间线:.

图表数据如下表所示。低效事件应显示为红色标记:

.

标签: rggplot2chartssequence

解决方案


这听起来像是geom_point代替 的工作geom_step,因为您希望将每个数据点显示为标记。

一些假数据:

library(dplyr); library(lubridate)

df <- tibble(
  robot = sample(2*1:33, 1E4, replace = TRUE),
  stepStartTime = ymd_hm(201809090000) +
    runif(1E4, 0, 60*60*24),
  effStatus = sample(c("Efficient", "Inefficient"),
                     1E4, replace = TRUE)
)

绘制它们:

ggplot(df, aes(stepStartTime, robot, color = effStatus)) +
  geom_point(size = 2, shape = 'I') +
  scale_y_reverse(breaks = 2*1:33) + 
  theme_minimal() +
  theme(panel.grid.major.y = element_blank(),
        panel.grid.minor.y = element_blank())

在此处输入图像描述

附录重新:手动颜色问题:要为每个机器人添加特定颜色(高效时)和低效时添加特殊颜色,您可以事先创建一个新变量,例如mutate(my_color = if_else(effStatus == "Inefficient", "Inefficient", robot). 然后my_colorrobot您指定颜色时参考。

要获得特定颜色,请使用scale_color_manual

https://ggplot2.tidyverse.org/reference/scale_manual.html


推荐阅读