小编mon*_*nis的帖子

如何阻止ggrepel标签在R/ggplot2中的gganimate帧之间移动?

我想在 ggplot 的行尾添加标签,避免它们重叠,并避免它们在动画过程中移动。

到目前为止,我可以将标签放在正确的位置并使用 保持它们静态geom_text,但标签重叠,或者我可以防止它们重叠使用geom_text_repel但标签不会出现在我希望它们出现的位置,然后在情节动画后跳舞(后一个版本在下面的代码中)。

我认为一个解决方案可能涉及在 ggplot(p1下)中有效地创建一个静态层,然后添加一个动画层(p2下),但似乎不是。

如何在动画 ggplot 中保存绘图常量(即静态)的某些元素?(在这种情况下,行尾的标签。)

此外,geom_text标签显示为我想要的 - 在每条线的末尾,在绘图之外 - 但是使用geom_text_repel,标签都在绘图区域内移动。为什么是这样?

以下是一些示例数据:

library(dplyr)
library(ggplot2)
library(gganimate)
library(ggrepel)

set.seed(99)

# data
static_data <- data.frame(
  hline_label = c("fixed_label_1", "fixed_label_2", "fixed_label_3", "fixed_label_4", 
                  "fixed_label_5", "fixed_label_6", "fixed_label_7", "fixed_label_8", 
                  "fixed_label_9", "fixed_label_10"), 
  fixed_score = c(2.63, 2.45, 2.13, 2.29, 2.26, 2.34, 2.34, 2.11, 2.26, 2.37))

animated_data <- data.frame(condition = c("a", "b")) %>% 
  slice(rep(1:n(), each = 10)) %>% 
  group_by(condition) %>% 
  mutate(time_point = row_number()) %>% …
Run Code Online (Sandbox Code Playgroud)

r ggplot2 gganimate ggrepel

5
推荐指数
1
解决办法
1279
查看次数

如何使用 R 中另一个数据帧的起始值和结束值对数据帧中的窗口进行子集化?

我有一个时间序列数据的数据框df1,我需要从 R 中提取多个“窗口”。我需要的窗口的起点和终点位于单独数据框 的两列中df2。起点和终点的值对应于所需窗口的行号。

在下面的示例中,我是解决方案的一部分,但目前仅提取第一个窗口。如何修改此示例以提取所有四个窗口?这可能是purrr的情况吗?

library(tidyverse)

# dataframe of data to subset
df1 <- tibble(my_values = rnorm(100))

# dataframe of windows (i.e. row number IDs) to extract from data
df2 <-tibble::tribble(
        ~window_start, ~window_end,
                   3L,         10L,
                  21L,         25L,
                  52L,         63L,
                  78L,         90L
        )

# extracted data
df3 <- df1 %>% 
  slice(df2$window_start : df2$window_end)

Run Code Online (Sandbox Code Playgroud)

(注意。我知道这里有一个类似的问题 -使用另一个数据帧的开始点和停止点对数据帧进行子集化? - 但我的实际数据非常大,我很好奇非基于合并的解决方案是否会更快。)

r subset dplyr purrr tidyverse

3
推荐指数
1
解决办法
350
查看次数

如何在ggplot中将十六进制代码传递给geom_hline?

在下面的代码中,我p1使用来自df1. 我想在score中每个项目的值处添加一条水平线df2,并使用列中包含的每个项目的相应十六进制代码为每条线着色item_hexcode

我认为将十六进制代码传递给 ggplot 以确定每行的颜色会很简单,但我似乎无法弄清楚如何去做。我尝试的每种方法要么抛出错误,要么似乎将十六进制代码视为因子的字符串/级别。

谁能指出我哪里出错了?

library(tidyverse)
# create example dataframes
set.seed(123)
df1 <- tibble(x = 1:5, y = (sample(200:300, 5, replace = TRUE)/100))
df2 <- tibble(item = c("a", "a", "b", "c", "b"), 
              score = c(2.58, 2.63, 2.45, 2.13, 2.29), 
              item_hexcode = c("#DA020E", "#DA020E", "#034694", "#7CFC00", "#034694"))

# initial plot
p1 <- ggplot(df1, aes(x, y)) + geom_line() + ylim(2, 3)
p1

# overlay horizontal lines on first plot, and colour …
Run Code Online (Sandbox Code Playgroud)

r colors ggplot2 geom-hline

1
推荐指数
2
解决办法
427
查看次数

标签 统计

r ×3

ggplot2 ×2

colors ×1

dplyr ×1

geom-hline ×1

gganimate ×1

ggrepel ×1

purrr ×1

subset ×1

tidyverse ×1