我在nycflights13软件包中为flights数据框的距离变量创建了一个直方图。
现在,我正在尝试向直方图添加一条垂直线以标记均值,如下所示:
library(nycflights13)
attach(flights)
ggplot(flights, aes(x = distance)) +
geom_histogram(aes(y = ..density..),
color = "darkblue",
fill = "lightblue",
binwidth = 250) +
labs(x = "Departure delay (minutes)") +
geom_vline(xintercept = mean(distance, color = black, size = 1.5)) +
geom_density(color = "red", size = 1)
这给了我输出:
Warning messages:
1: In mean.default(distance, color = black, size = 1.5) :
argument is not numeric or logical: returning NA
2: Removed 1 rows containing missing values (geom_vline).
我该如何解决?我尝试删除NA值,但我猜想方法不正确。
答案 0 :(得分:2)
您需要放入mean
作为标量。因此,我们可以在此处使用$
。将颜色作为字符串"black"
。
library(nycflights13)
# attach(flights) # I strongly recommend not to use attach
library(ggplot2)
ggplot(flights, aes(x = distance)) +
geom_histogram(aes(y = ..density..),
color = "darkblue",
fill = "lightblue",
binwidth = 250) +
labs(x = "Departure delay (minutes)") +
geom_vline(xintercept = mean(flights$distance),
color="black", size=1.5) +
geom_density(color = "red", size = 1)