使用geom_text和子集在ggplot2中进行条件标记

时间:2016-04-11 18:09:58

标签: r ggplot2

我是社区的新手,我在搜索在线提到的解决方案时多次尝试后发布此内容。但是,我无法解决它。

以下代码

import os
import zipfile
import sys

def usage():
    print "\nHow to use warmaker.py"
    print 'Usage: ' + sys.argv[0] + ' -i <inputfile> -o <outputfile> '


def unzip(ifile):
    print 'Before' + ifile
    ifile = os.path.splitext(ifile)[0] + ".zip"
    print 'after' + ifile
    print 'Changing extension from ' + ifile + 'to ' + ifile
    print '\nStart to unzip ' + ifile
    print " ..."
    extract = zipfile.ZipFile(ifile)
    extract.extractall('.')
    print ifile + 'successfully extracted'
    extract.close()

这给了我以下结果:

enter image description here

但是,当我将以下行添加到代码

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

我收到以下错误

错误:美学必须是长度1或与数据(27)相同:x,y,标签

有人可以帮我这个吗?

数据来自Harvard Tutorial on GGPLOT2

有关您的信息,数据集的结构如下

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

1 个答案:

答案 0 :(得分:6)

首先,请勿在{{1​​}}中使用$。 然后,修复子集部分尝试..

aes()

..希望得到你想要的情节: enter image description here