我正在try 绘制R中一个大型时间序列数据集的2个变量的散点图,我想突出显示其中一个月的数据,并将其提前显示. 我已经在论坛上try 了一些建议的解决方案,但它们似乎不起作用(可能是因为问题有点陈旧,一些论点可能会在新版本中改变). 到目前为止,我有这样的 idea :

set.seed(123)

date=seq(as.POSIXct("2022-04-01 00:00:00"), as.POSIXct("2022-10-31 23:00:00"), by = "hour")
t= abs(rnorm(length(date)))
y= exp(t)+ rnorm(length(date), mean = 0, sd = 3)

df<-data.frame(date=date,t=t,y=y)

df$month<-month(df$date)

highlight_month <- 1 
non_highlighted_colors <- rep("grey", length(unique(df$month)))
non_highlighted_colors[highlight_month] <- "red"
df$order<-ifelse(df$month==highlight_month,1,2)

ggplot(df, aes(t, y)) +
  geom_point(aes(color = factor(month),order=order)) +
  scale_color_manual(values = non_highlighted_colors) +
  labs(color = "Month") +
  theme_minimal()

第一件事就是命令被忽略了.我想这可能是因为我注意到如果我在代码中突出显示month 1,这意味着month 4,当我运行order时,它会搜索一月,而数据中没有.

这就是代码不起作用的原因吗?

谢谢你的建议

推荐答案

通过将 colored颜色 映射到条件并指定手动色标,可以使Things变得更简单:

ggplot(df, aes(t, y)) +
geom_point(aes(colour = month == 4)) +
scale_colour_manual(values = c("grey", "red")) +
labs(colour = "Month") +
theme_minimal()

plot1

但是你可能想把突出显示的点放在前面,所以你需要把绘图分成两个geom_point,以确保突出显示的点画在灰色点的后面(即顶部):

ggplot(df, aes(t, y)) +
  geom_point(data = df[df$month != 4, ], aes(colour = month == 4)) +
  geom_point(data = df[df$month == 4, ], aes(colour = month == 4)) +
  scale_colour_manual(values = c("grey", "red")) +
  labs(colour = "Month") +
  theme_minimal()

plot2

你可能想要一个更好的图例,所以你可以做一些事情,比如构造一个带有高亮显示条件的factor变量,并将其映射到color:

df$highlight <- factor(df$month == 4,
                       levels = c(T, F),
                       labels = c("April", "Other"))

ggplot(df, aes(t, y)) +
  geom_point(data = df[df$highlight == "Other", ], aes(colour = highlight)) +
  geom_point(data = df[df$highlight == "April", ], aes(colour = highlight)) +
  scale_colour_manual(values = c("grey", "red")) +
  labs(colour = "Month") +
  theme_minimal()

plot3

但由于传说的顺序就是情节的顺序,所以Other在传说中排在第一位,看起来很奇怪.可以通过指定色标的分隔符和值来更正它:

ggplot(df, aes(t, y)) +
  geom_point(data = df[df$highlight == "Other", ], aes(colour = highlight)) +
  geom_point(data = df[df$highlight == "April", ], aes(colour = highlight)) +
  scale_colour_manual(breaks = c("April", "Other"),
                      values = c("red", "grey")) +
  labs(colour = "Month") +
  theme_minimal()

enter image description here

R相关问答推荐

如何在弹性表中为类别值的背景上色

在R中列表的结尾添加数字载体

基于现有类创建类的打印方法(即,打印tibles更长时间)

使用tidyverse / Mutate的存款账户余额

无法将传奇添加到cowplot多情节中

如何根据条件计算时差(天)

ggplot2中的X轴显示数值,单位为百,而不是十

在数组索引上复制矩阵时出错

可以替代与NSE一起使用的‘any_of()’吗?

比较理论阿尔法和经验阿尔法

从服务器在Shiny中一起渲染图标和文本

如何通过匹配R中所有可能的组合来从宽到长旋转多个列?

当我添加美学时,geom_point未对齐

按时间顺序对不同事件进行分组

在多页PDF中以特定布局排列的绘图列表不起作用

使用来自嵌套列和非嵌套列的输入的PURRR:MAP和dplyr::Mariate

是否有一个R函数可以输出在输入的字符向量中找到的相应正则表达式模式?

如何更改包中函数中的参数?

如何使用循环从R中的聚合函数创建列,而不会在名称中给出&q;$&q;?

删除r中每个因素级别的最后2行