基于条件的标签图

Label plot based on condition

我有一个点图,其中包含来自数据框 df_roles$result 的数据,并且只想将标签分配给在 df_roles$name.

中由其特定名称指定的某些点

我的预期输出是中国标示。

这两个参数我都试过了,但都不行:

ifelse(df_roles$name = "China", 
text(df_roles[[3]], df_roles[[2]], labels = df_roles[[1]], pos = 2, cex=0.3), " ")

geom_text(data = filter(df_roles$result, df_roles$name=="China"),aes(label=df_roles$name))

可重现的例子:

df_roles <- structure(list(name = structure(1:6, .Label = c("Afghanistan", 
"Albania", "Algeria", "Angola", "Argentina", "Armenia", "Australia", 
"Austria", "Azerbaijan", "Bahrain", "Bangladesh", "Barbados", 
"Belarus", "Belgium", "Belize", "Benin", "Bolivia", "Bosnia and Herzegovina", 
"Botswana", "Brazil", "Bulgaria", "Burkina Faso", "Burundi", 
"Cameroon", "Canada", "Chile", "China", "Colombia", "Congo", 
"Costa Rica", "Croatia", "Cuba", "Cyprus", "Democratic Republic of the Congo", 
"Denmark", "Dominican Republic", "Ecuador", "Egypt", "El Salvador", 
"Eritrea", "Estonia", "Ethiopia", "Finland", "France", "Gabon", 
"Gambia", "Georgia", "Germany", "Ghana", "Greece", "Grenada", 
"Guatemala", "Guinea", "Guyana", "Haiti", "Honduras", "Hungary", 
"India", "Indonesia", "Iran ", "Iraq", "Ireland", "Israel", "Italy", 
"Jamaica", "Japan", "Jordan", "Kazakhstan", "Kenya", "Kuwait", 
"Kyrgyzstan", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", 
"Lithuania", "Luxembourg", "Malawi", "Malaysia", "Mali", "Malta", 
"Mauritania", "Mexico", "Mongolia", "Montenegro", "Morocco", 
"Mozambique", "Namibia", "Nepal", "Netherlands", "New Zealand", 
"Nicaragua", "Nigeria", "Norway", "Oman", "Pakistan", "Palestine", 
"Panama", "Paraguay", "Peru", "Philippines", "Poland", "Portugal", 
"Qatar", "Republic of Korea", "Republic of Moldova", "Romania", 
"Russia", "Rwanda", "Saint Lucia", "Saint Vincent and the Grenadines", 
"Saudi Arabia", "Senegal", "Serbia", "Singapore", "Slovakia", 
"Slovenia", "Somalia", "South Africa", "Spain", "Sri Lanka", 
"Sudan", "Suriname", "Sweden", "Switzerland", "Syria", "Taiwan", 
"Tajikistan", "Thailand", "Togo", "Trinidad and Tobago", "Tunisia", 
"Turkey", "Turkmenistan", "Uganda", "UK", "Ukraine", "United Arab Emirates", 
"United Republic of Tanzania", "United States of America", "Uruguay", 
"Uzbekistan", "Venezuela", "Viet Nam", "Yemen", "Zambia", "Zimbabwe"
), class = "factor"), result = c(0.0900102874778869, -0.0934265332577318, 
-0.177974826946747, -0.590024694573266, 1.20884852383168, -0.183452483887309
)), row.names = c(NA, 6L), class = "data.frame")

由于共享的数据中没有'China',所以我以'Afghanistan'为例。还使用行号作为 x 轴。

library(dplyr)
library(ggplot2)

df_roles %>%
  mutate(name = as.character(name), 
         label = replace(name, name != 'Afghanistan', ''), 
         row = row_number()) %>%
  ggplot(aes(row, result, label = label)) + 
  geom_point() + geom_text(vjust = -0.5)