gpt4 book ai didi

r - ggplot2 中使用 geom_text 和子集的条件标记

转载 作者:行者123 更新时间:2023-12-05 01:37:05 25 4
gpt4 key购买 nike

我是社区的新手,在搜索在线提到的解决方案时,我在多次尝试之后发布了这个。但是,我一直无法解决它。

以下代码

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))

这给了我以下结果:

enter image description here

但是,当我将以下几行添加到代码中时
pointsToLabel <- 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")

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

我收到以下错误

错误:Aesthetics 必须为长度 1 或与数据 (27) 相同:x, y, label

有人可以帮我弄这个吗?

数据来源于 Harvard Tutorial on GGPLOT2

供您引用,数据集的结构如下
'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 ...

最佳答案

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

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

.. 希望能产生你想要的情节:
enter image description here

关于r - ggplot2 中使用 geom_text 和子集的条件标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36556087/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com