美学必须是长度一,或与数据相同的长度

时间:2017-07-19 12:59:37

标签: r ggplot2

我正在尝试制作散点图,但不断得到错误"美学必须是长度为1或与数据相同的长度。"我已经查看了与此相关的其他问题,但似乎无法弄清楚如何在这里应用它们。该问题特别适用于尝试添加第二层。以下代码工作正常:

scatter1 <- ggplot(ratios3, aes(ratios3$`CPI-U 2015 (Official)`, 
        ratios3$`PCE1 2015`)) + 
    geom_point(shape=1) +
    theme_bw()
scatter1 + 
    labs(title="Relationship Between CPI RI and PCE RI \n(Unadjusted)", 
        x = "CPI RI", y = "Unadj. PCE RI") +
    theme(plot.title = element_text(hjust = 0.5, family="Times")) +
    theme(axis.text = element_text(family = "Times"), 
        axis.title.x = element_text(family = "Times", face = "plain", size = 
        12), axis.title.y = element_text(family = "Times", face = "bold", 
        size = 12)) +
    theme(axis.line = element_line(color = "black")) +
    geom_abline(intercept = 0, slope = 1) +
    scale_x_continuous(breaks = c(0, .05, .1, .15, .2, .25)) +
    scale_y_continuous(breaks = c(0, .05, .1, .15, .2, .25)) +
    annotate(geom="text", x=.195, y=.120, label="Owners' Equivalent Rent", 
        size=3, family="Times") +
    annotate(geom="text", x=.077, y=.040, label="Rent", size=3, 
        family="Times") +
    annotate(geom="text", x=.022, y=.100, label="Hospital Services", size=3, 
        family="Times") +
    annotate(geom="text", x=.029, y=.048, label="Physicians' Services", 
        size=3, family="Times") +
    annotate(geom="text", x=.025, y=.032, label="Prescription Drugs", 
        size=3, family="Times")

我想要做的是突出显示数据框中的异常值。虽然似乎有其他方法可以为某些点着色而不是下面的代码,但这似乎是最干净和最简单的;此外,我尝试了多个其他选项也无济于事。根据建议,这是我添加的内容(在创建数据框&#34;异常值&#34;之后):

geom_point(data = outliers, colour = "red", shape=1) +

这样做会产生以下错误:

Error: Aesthetics must be either length 1 or the same as the data (7): x, y

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

Ben的评论让我思考变量名,我意识到异常值中没有指定的变量(原始数据框,比率3和异常值都有很多变量)。我只需要指定相同的变量:

  geom_point(data = outliers, aes(`CPI-U 2015 (Official)`, `PCE1 2015`), 
      colour = "red", shape=1) +