繁体   English   中英

R:您可以在不覆盖数据点的情况下将 label 添加到反应性 ggplot 中吗?

[英]R: Can you add a label to reactive ggplot without covering data points?

我正在编写一个 shiny 应用程序,该应用程序呈现来自用户上传的 csv 的 ggplot。 我需要在图表上添加一个 label。 label 去哪里并不重要,只要它不掩盖任何数据点。 我遇到麻烦的原因是因为上传的 csv 的规模/分布是未知的,所以我事先不知道放置 label 的好地方在哪里,我不知道如何让它移动到避免与点重叠。

到目前为止,我尝试的是扩展图表,使 x 轴比需要的大 1 个标准差,这样我就可以将 label 一直放在右边,并确保那里没有数据点重叠. 这行得通,但在美学上不是很讨人喜欢。

这是我拥有的代码:

df        # uploaded data frame
x1, x2    # columns of the data frame 

 ggplot(data=df2, aes(x=x1, y=x2))+
        geom_point()+
        xlim(min(df$x1), max(df$x1)+sd(df$x1))+
        annotate(geom="label", x=max(df$x1)-sd(df$x1), y=min(df$x2), label="words"))

这个问题有很多潜在的解决方案; 也许ggrepel package( https://cran.r-project.org/web/packages/ggrepel/vignettes/ggrepel.ZFC35FDC70D5FC69D269883A822C7A5 )可以解决问题? 例如

library(tidyverse)
library(ggrepel)
library(palmerpenguins)

penguins %>% 
  na.omit() %>%
  # arrange the df by your y variable
  arrange(desc(bill_length_mm)) %>% 
  # create a new variable (called "label_one_point")
  # and give the single highest y variable point a label
  mutate(label_one_point = ifelse(bill_length_mm == first(bill_length_mm),
                                  "PENGUINS!! \n(or whatever label you want)", NA)) %>% 
  # plot the thing
  ggplot(aes(x = flipper_length_mm, y = bill_length_mm)) +
  geom_point() +
  geom_text_repel(aes(label = label_one_point),
                  # you can move the label closer or further away
                  point.padding = unit(20, "cm"),
                  # and you probably don't want a 'segment', so set this high
                  # a segment is a line attaching a geom_text to it's point
                  min.segment.length = unit(20, "cm"),
                  force_pull = 0.1, size = 5,
                  show.legend = FALSE) +
  theme_light()

示例_1.png

暂无
暂无

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

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