【问题标题】:Using different data for positioning and display of labels in plots使用不同的数据在图中定位和显示标签
【发布时间】:2020-10-13 13:48:34
【问题描述】:

TL;DR:对于使用geom_label 等的绘图标签,是否可以使用不同的数据来计算使用position_stack 或类似函数的位置,而不是显示标签本身?或者,不太一般,是否可以在计算出位置后对标签数据进行子集化?

我有许多不同主题的时间序列数据。观察发生在多个时间点,对于每个受试者来说都是相同的。我想将此数据绘制为堆积面积图,其中受试者曲线在每个时间点的高度对应于该受试者在该时间点的观察值。 至关重要的是,我还需要添加标签来识别每个主题。

但是,在每次观察中添加一个标签的简单解决方案会使绘图不可读,因此我想将显示的标签限制为“最重要”的主题(具有最高峰值的主题),以及仅在相应的峰值处显示标签。标签本身的这种子集也不是问题,但我无法弄清楚如何正确定位标签(子集),以便它们与堆叠面积图匹配。

这是一些示例代码,它应该可以在安装了tidyverse 的情况下立即使用,以说明我的问题。首先,我们生成一些与我的结构相同的数据:

library(tidyverse)
set.seed(0)

# Generate some data
num_subjects = 50
num_timepoints = 10
labels = paste(sample(words, num_subjects), sample(fruit, num_subjects), sep = "_")
col_names = c("name", paste0("timepoint_", c(1:num_timepoints)))
df = bind_rows(map(labels,
                   ~c(., cumsum(rnorm(num_timepoints))) %>%
                     set_names(col_names))) %>%
  pivot_longer(starts_with("timepoint_"), names_to = "timepoint", names_prefix = "timepoint_") %>%
  mutate(across(all_of(c("timepoint", "value")), as.numeric)) %>%
  mutate(value = if_else(value < 0, 0, value)) %>%
  group_by(name) %>% mutate(peak = max(value)) %>% ungroup()

现在,我们可以简单地制作一个没有标签的简单堆叠面积图:

# Plot (without labels)
ggplot(df,
       mapping = aes(x = factor(timepoint), y = value, group = name, fill = factor(peak))) +
  geom_area(show.legend = FALSE, position = "stack", colour = "gray25") +
  scale_fill_viridis_d()

Plot without labels (it appears that I currently cannot embed images, which is very unfortunate as they are extremely illustrative here...)

为这些数据添加非特定标签也不是太难。使用position_stack:

# Plot (all labels, positions are correct but the plot is basically unreadable)
ggplot(df,
       mapping = aes(x = factor(timepoint), y = value, group = name, fill = factor(peak))) +
  geom_area(show.legend = FALSE, position = "stack", colour = "gray25") +
  geom_label(mapping = aes(label = name), show.legend = FALSE, position = position_stack(vjust = 0.5)) +
  scale_fill_viridis_d()

Plot with a label at each observation

但是,如前所述,标签几乎完全掩盖了情节本身。所以我的方法是只在峰值处显示标签,并且只针对峰值最高的 10 个主题:

# Plot (only show labels at the peak for the 10 highest peaks, readable but positions are wrong)
max_labels = 10 # how many labels to show
df_labels = df %>%
  group_by(name) %>% slice_max(value, n = 1) %>% ungroup() %>%
  slice_max(value, n = max_labels)

ggplot(df,
       mapping = aes(x = factor(timepoint), y = value, group = name, fill = factor(peak))) +
  geom_area(show.legend = FALSE, position = "stack", colour = "gray25") +
  geom_label(data = df_labels, mapping = aes(label = name), show.legend = FALSE, position = position_stack(vjust = 0.5)) +
  scale_fill_viridis_d()

Plot with only a subset of labels

这段代码也可以正常工作,但很明显标签不再显示在正确的位置,而是在图上太低了,特别是对于否则会更高的主题。 (位置正确的唯一主题是work_eggplant。)这很有意义,因为用于计算position_stack 的数据现在只是原始数据的一个子集,因此不会收到标签的观察结果不是堆叠时考虑。这可以通过将所有不会收到标签的观察归零来说明:

df_zeroed = anti_join(df %>% mutate(value = 0),
                      df_labels,
                      by = c("name", "timepoint")) %>% bind_rows(df_labels)
ggplot(df_zeroed,
       mapping = aes(x = factor(timepoint), y = value, group = name, fill = factor(peak))) +
  geom_area(show.legend = FALSE, position = "stack", colour = "gray25") +
  geom_label(data = df_labels, mapping = aes(label = name), show.legend = FALSE, position = position_stack(vjust = 0.5)) +
  scale_fill_viridis_d()

Plot with unlabeled observations zeroed out

所以现在我的问题是,如何解决这个问题?有没有办法将原始数据用于定位,而将子集数据用于标签的实际显示?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    也许这就是你要找的。为了达到预期的效果,您可以

    1. 使用整个数据集绘制标签以获得正确的位置,
    2. 对不需要的标签使用空字符串"",
    3. 将不需要的标签的fill 和color 设置为"transparent"
    # Plot (only show labels at the peak for the 10 highest peaks, readable but positions are wrong)
    max_labels = 10 # how many labels to show
    df_labels = df %>%
      group_by(name) %>% 
      slice_max(value, n = 1) %>% 
      ungroup() %>%
      slice_max(value, n = max_labels) %>% 
      mutate(label = name)
    
    df1 <- df %>% 
      left_join(df_labels) %>% 
      replace_na(list(label = ""))
    #> Joining, by = c("name", "timepoint", "value", "peak")
    
    ggplot(df1,
           mapping = aes(x = factor(timepoint), y = value, group = name, fill = as.character(peak))) +
      geom_area(show.legend = FALSE, position = "stack", colour = "gray25") +
      geom_label(mapping = aes(
        label = label,
        fill = ifelse(label != "", as.character(peak), NA_character_),
        color = ifelse(label != "", "black", NA_character_)), 
        show.legend = FALSE, position = position_stack(vjust = 0.5)) +
      scale_fill_viridis_d(na.value = "transparent") +
      scale_color_manual(values = c("black" = "black"), na.value = "transparent")
    

    编辑如果您希望填充颜色对应于峰值的值,那么

    1. 一个简单的解决方案是将peak 映射到fill 而不是factor(peak),并在geom_label 中使用fill = ifelse(label != "", peak, NA_real_)。但是,在这种情况下,您必须切换到连续填充比例。

    2. 我猜您有充分的理由使用离散比例,另一种选择是将peak 设为有序因子。然而,这种方法并不是那么简单。为了完成这项工作,我首先根据峰值对factor(peak) 重新排序,添加一个额外的 NA 级别,并使我们使用一个辅助变量peak1 来填充标签。但是,由于我们要在 fill 上映射两个不同的变量,我建议使用 ggnewscale::new_scale_fill 使用第二个填充比例来实现所需的结果:

    library(tidyverse)
    set.seed(0)
    #cumsum(rnorm(num_timepoints)) * 3
    # Generate some data
    num_subjects = 50
    num_timepoints = 10
    labels = paste(sample(words, num_subjects), sample(fruit, num_subjects), sep = "_")
    col_names = c("name", paste0("timepoint_", c(1:num_timepoints)))
    df = bind_rows(map(labels,
                       ~c(., cumsum(rnorm(num_timepoints)) * 3) %>%
                         set_names(col_names))) %>%
      pivot_longer(starts_with("timepoint_"), names_to = "timepoint", names_prefix = "timepoint_") %>%
      mutate(across(all_of(c("timepoint", "value")), as.numeric)) %>%
      mutate(value = if_else(value < 0, 0, value)) %>%
      group_by(name) %>% mutate(peak = max(value)) %>% ungroup()
    
    # Plot (only show labels at the peak for the 10 highest peaks, readable but positions are wrong)
    max_labels = 10 # how many labels to show
    df_labels = df %>%
      group_by(name) %>% 
      slice_max(value, n = 1) %>% 
      ungroup() %>%
      slice_max(value, n = max_labels) %>% 
      mutate(label = name)
    
    df1 <- df %>% 
      left_join(df_labels) %>% 
      replace_na(list(label = ""))
    #> Joining, by = c("name", "timepoint", "value", "peak")
    
    
    df2 <- df1 %>% 
      mutate(
        # Make ordered factor
        peak = fct_reorder(factor(peak), peak),
        # Add NA level to peak
        peak = fct_expand(peak, NA),
        # Auxilliary variable to set the fill to NA for non-desired labels
        peak1 = if_else(label != "", peak, factor(NA))) 
    
    ggplot(df2, mapping = aes(x = factor(timepoint), y = value, group = name, fill = peak)) +
      geom_area(show.legend = TRUE, position = "stack", colour = "gray25") +
      scale_fill_viridis_d(na.value = "transparent") +
      # Add a second fill scale
      ggnewscale::new_scale_fill() +
      geom_label(mapping = aes(
        label = label,
        fill = peak1, 
        color = ifelse(label != "", "black", NA_character_)), 
        show.legend = FALSE, position = position_stack(vjust = 0.5)) +
      scale_fill_viridis_d(na.value = "transparent") +
      scale_color_manual(values = c("black" = "black"), na.value = "transparent")
    

    【讨论】:

    • 谢谢,这个解决方案没有我希望的那么干净,但它确实解决了我的问题。但是,这样做似乎会导致峰值(以及颜色分配)按字母顺序而不是数字顺序排序。如果您使用更高的值(例如cumsum(rnorm(num_timepoints)) * 3),可以看到这一点:i.imgur.com/eWdFYhN.png(这里我还启用了图例,所以它特别明显)。你知道如何解决这个问题吗?
    • 你好 Shizundeiku。嗯。据我所知,这是实现您想要的结果的最干净的解决方案。 (;关于填充颜色。这不是我的解决方案的问题。我只是从你的代码中借用这个,即你在fill上映射factor(peak),而我使用as.character(fill)。但这没关系。两个结果按字母顺序排列。我刚刚进行了编辑,其中包括解决此问题的两个选项。
    猜你喜欢
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多