繁体   English   中英

R:将标签添加到气泡 Plot?

[英]R: Adding Labels to a Bubble Plot?

我正在使用 R 编程语言。 我发现这个非常好的教程展示了如何使用 ggplot 库制作气泡图: https://www.data-to-viz.com/graph/bubble.html

# Libraries
library(tidyverse)
library(hrbrthemes)
library(viridis)
library(gridExtra)
library(ggrepel)
library(plotly)

# The dataset is provided in the gapminder library
library(gapminder)
data <- gapminder %>% filter(year=="2007") %>% dplyr::select(-year)

# Prepare data
tmp <- data %>%
 mutate(
   annotation = case_when(
    gdpPercap > 5000 & lifeExp < 60 ~ "yes",
    lifeExp < 30 ~ "yes",
     gdpPercap > 40000 ~ "yes"
    )
) %>%
mutate(pop=pop/1000000) %>%
  arrange(desc(pop)) %>%
  mutate(country = factor(country, country))


 
    # Plot
   my_plot = ggplot( tmp, aes(x=gdpPercap, y=lifeExp, size = pop, color = continent)) +
        geom_point(alpha=0.7) +
        scale_size(range = c(1.4, 19), name="Population (M)") +
        scale_color_viridis(discrete=TRUE) +
        theme_ipsum() +
        theme(legend.position="none") +
        geom_text_repel(data=tmp %>% filter(annotation=="yes"), aes(label=country), size=4 )

在此处输入图像描述

我想把它变成一个交互式 plotly plot,但保留一些标签/标题。 我试图用“ggplotly”function 来做到这一点:

ggplotly(my_plot)

在此处输入图像描述

但是正如我们在这里看到的,标签(例如南非、美国)已经消失了? 有没有办法恢复这些标签并将 plot 保留为交互式图?

谢谢!

请参阅具有类似问题的最近线程

根据警告消息:

geom_GeomTextRepel() 尚未在 plotly 中实现

要解决这个问题,您可以改用geom_text并使用y/x值:

my_plot = ggplot( tmp, aes(x=gdpPercap, y=lifeExp, size = pop, color = continent)) +
  geom_point(alpha=0.7) +
  scale_size(range = c(1.4, 19), name="Population (M)") +
  scale_color_viridis(discrete=TRUE) +
  theme_ipsum() +
  theme(legend.position="none") +
  geom_text(data=tmp %>% filter(annotation=="yes"), aes(y=lifeExp-1.5, label=country), size=4 )

ggplotly(my_plot)

在此处输入图像描述

暂无
暂无

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

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