【问题标题】:Geom_text() in R - how to change a label position of a specific dot in geom_pointR 中的 Geom_text() - 如何更改 geom_point 中特定点的标签位置
【发布时间】:2021-01-30 20:03:25
【问题描述】:

我正在努力改变 ggplot 中 geom_point 中几个点标签的位置。到目前为止,我的代码:

p <- ggplot(all_short_filled, aes(x=Modernization, y=Passionate_love)) + 
  geom_point(size=2)+geom_abline(intercept = 0.965830, slope = -0.001127)+  theme_bw()

p1 <- p + geom_text(label=all_short_filled$Country, position = position_dodge(width = 1),
                    vjust = -0.5)
p1

它给了我这样的东西: 我想更改一些重叠标签的位置(例如俄罗斯和塞尔维亚,或荷兰和比利时,例如,塞尔维亚的标签将位于点下方,而不是上方)。请发送帮助:-)

【问题讨论】:

  • 看看ggrepel 包。
  • 嘿马库斯,我做到了。但结果远非完美(事实上,没有排斥更好):)
  • 对于这些国家/地区,您可以将 all_short_filled$Country 设置为 NA""。然后为他们创建第二个数据集并添加另一个geom 层:geom_text(data = countries_belowdot, ..., vjust = 1)

标签: r ggplot2 geom-text


【解决方案1】:

您可以在数据集中创建两个标签列:一个用于应在其点上方绘制的国家/地区,另一个用于下方。由于我没有您的数据样本,因此我使用mtcars 数据集创建了一个可重现的示例:

这将要求您知道哪些国家/地区是硬编码的。

library(datasets) # used to create fake data
library(tidyverse)

# create fake dataset for example
df <- tail(datasets::mtcars) %>% 
  tibble::rownames_to_column("car")

below <- c("Ferrari Dino", "Maserati Bora")

# create two columns for geom_text labels
data <- df %>% 
  dplyr::mutate(label_above = ifelse(car %in% below, "", car),
                label_below = ifelse(car %in% below, car, ""))

# ignore scale_x.. and scale_y.. those were to fit points/labels neatly
ggplot2::ggplot(data, aes(x = hp, y = mpg)) + 
  geom_point() + 
  geom_text(aes(label = label_above), vjust = -0.5) + # labels above their points
  geom_text(aes(label = label_below), vjust = 1) +  # labels below their points
  scale_x_continuous(expand = ggplot2::expansion(0.3)) + 
  scale_y_continuous(expand = ggplot2::expansion(0.15))

话虽如此,正如 cmets 中提到的那样,ggrepel 通常非常擅长处理这类事情。

【讨论】:

    猜你喜欢
    • 2021-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-20
    相关资源
    最近更新 更多