R 使用geom_文本和子集在ggplot2中进行条件标记

R 使用geom_文本和子集在ggplot2中进行条件标记,r,ggplot2,R,Ggplot2,我是这个社区的新成员,我在网上搜索所提到的解决方案时多次尝试过这个问题,现在就发布这个帖子。然而,我还没能解决它 下面的代码 dat<-read.csv("Harvard tutorial/Rgraphics/dataSets/EconomistData.csv") g <- ggplot(dat, aes(dat$CPI, dat$HDI)) g1 <- g + theme_bw() + geom_smooth(method = "lm", formula = y ~log

我是这个社区的新成员,我在网上搜索所提到的解决方案时多次尝试过这个问题,现在就发布这个帖子。然而,我还没能解决它

下面的代码

dat<-read.csv("Harvard tutorial/Rgraphics/dataSets/EconomistData.csv")
g <- ggplot(dat, aes(dat$CPI, dat$HDI))

g1 <- g + theme_bw() + geom_smooth(method = "lm", formula = y ~log(x), se = FALSE, color = "Red", linetype = 1, weight = 3) +
  geom_point(aes(color = Region), size = 4, fill = 4, alpha = 1/2, shape = 1) +
  scale_x_continuous(name = "Corruption Perception Index", breaks = NULL) +
  scale_y_continuous(name = "Human Development Index") +
  scale_color_manual(name = "Region of the world", values = c("#24576D", "#099DD7", "#28AADC", "#248E84", "#F2583F", "#96503F")) + 
  theme(axis.text.x = element_text(angle = 90, size = 15))

首先,不要在
aes()
中使用
$
。 然后,要修复子集部分,请尝试

g2 <- g1 + 
  geom_text(aes(CPI, HDI, label = Country), data = dat[dat$Country %in% pointsToLabel,])

g2首先,应避免在
aes
中使用
data$column
。只需使用列名,因为您已经在
ggplot(data=dat)
中指示了要使用的数据。其次,您可以在
dat
中使用
pointsToLabel
向量(未标记的点为空格或NAs)创建一列,然后将该列指定为ggplot中的标签。谢谢您的建议!!谢谢各位。这是成功的。我还通过使用dplyr库中的过滤器使其工作。
'data.frame':   173 obs. of  6 variables:
 $ X       : int  1 2 3 4 5 6 7 8 9 10 ...
 $ Country : Factor w/ 173 levels "Afghanistan",..: 1 2 3 4 5 6 7 8 9 10 ...
 $ HDI.Rank: int  172 70 96 148 45 86 2 19 91 53 ...
 $ HDI     : num  0.398 0.739 0.698 0.486 0.797 0.716 0.929 0.885 0.7 0.771 ...
 $ CPI     : num  1.5 3.1 2.9 2 3 2.6 8.8 7.8 2.4 7.3 ...
 $ Region  : Factor w/ 6 levels "Americas","Asia Pacific",..: 2 3 5 6 1 3 2 4 3 1 ...
g2 <- g1 + 
  geom_text(aes(CPI, HDI, label = Country), data = dat[dat$Country %in% pointsToLabel,])