在 R 中使用 ggplot2 向绘图添加标签

Adding labels to a plot using ggplot2 in R

我在使用 geom_text_repel 向绘图添加标签时遇到错误。以下是添加任何文本标签之前的代码,一切正常:

[输入]

library(ggplot2)
library(ggrepel)
library(ggthemes)
library(scales)
library(plotly)
library(grid)
library(extrafont)

#read data
econ <- read.csv("https://raw.githubusercontent.com/altaf-ali/ggplot_tutorial/master/data/economist.csv")

#Data Visualisation
g <- ggplot(econ, aes(CPI,HDI))+geom_smooth(se = FALSE, method = 'lm', fullrange=T,formula=y~log(x), color='red')+
  geom_point(stroke=0,color='white',size=3,show.legend = T)

g <- g+ geom_point(aes(color=Region),size=3,pch=1,stroke=1.2)

g <- g+theme_economist()
g <- g+scale_x_continuous(limits = c(1,10), breaks = 1:10)+
  scale_y_continuous(limits = c(0.2,1.0),breaks=seq(0.2,1.0,0.1))
  labs(title = 'Corruption and human development',
        caption='Source: Transparency International; UN Human Development Report')


g <- g+xlab('Corruption Perceptions Index, 2011 (10=least corrupt)')+
  ylab('Human Development Index, 2011 (1=best)')
g <- g+theme(plot.title = element_text(family = 'Arial Narrow', size=14,margin=margin(0,0,12,0)),
           plot.caption = element_text(family = 'Arial Narrow', hjust=0, margin=margin(10,0,0,0)),
           axis.title.x = element_text(family='Arial Narrow', face = 'italic',size=8, margin=margin(10,0,10,0)),
           axis.title.y = element_text(family='Arial Narrow', face = 'italic',size=8, margin=margin(0,10,0,10))
) 

g
grid.rect(x=0.026, y=0.9,hjust = 1,vjust=0,gp=gpar(fill='#e5001c',lwd=0))

[输出]

然后,我试图在图上标记一些主要国家,所以我首先通过这样做创建了一个子数据集:

target_countries <- c(
  "Russia", "Venezuela", "Iraq", "Myanmar", "Sudan",
  "Afghanistan", "Congo", "Greece", "Argentina", "Brazil",
  "India", "Italy", "China", "South Africa", "Spane",
  "Botswana", "Cape Verde", "Bhutan", "Rwanda", "France",
  "United States", "Germany", "Britain", "Barbados", "Norway", "Japan",
  "New Zealand", "Singapore"
)
labeled_countries <- subset(econ, Country %in% target_countries)

我得到这个:Error: Aesthetics must be either length 1 or the same as the data (173): x, y 当我尝试使用 geom_text_repel 将这些名称添加到我的情节时:

g <- g+geom_text_repel(aes(labeled_countries))

我想要的输出是模仿这个经济学家图表:

如何解决错误?

如果我的问题足够清楚,请告诉我。

感谢任何帮助!

设置新的datalabeled_countriesaestheticlabel.

g + geom_text_repel(data = labeled_countries, aes(CPI, HDI, label = Country))