r:无法用NA绘制数据帧

时间:2017-06-16 20:16:32

标签: r ggplot2

(早先发表这篇文章并忘记包含一个可重现的例子。)

我合并了两个带有左连接的数据帧,以构建一个相当大的数据帧。我现在尝试使用ggplot2来绘制数据框中的两列,但其中一列似乎没有正确绘图。它以x = 400结束,即使它有足够的y值,其x值超过400。

这是一些示例数据。这是一个较大数据帧的示例,因此图表看起来很奇怪。

irradiance <- data.frame(
    lambda = c(337, 337.5, 338, 400, 400.5, 401, 401.5, 650, 650.5, 651),
    date = as.Date("2016-07-19"),
    Local_irrad = c(.159, .175, .182, .315, .326, .335, .342, .248, .246, .248),
    Global_horizn_irradiance = c(.4942, .5295, .5682, 1.232, NA, 1.281, NA, 1.249, NA, 1.326))

lambda  date        Local_irrad  Global_horizn_irradiance
337     7/19/2016   0.159        0.4942
337.5   7/19/2016   0.175        0.5295
338     7/19/2016   0.182        0.5682
400     7/19/2016   0.315        1.232
400.5   7/19/2016   0.326        NA
401     7/19/2016   0.335        1.281
401.5   7/19/2016   0.342        NA
650     7/19/2016   0.248        1.249
650.5   7/19/2016   0.246        NA
651     7/19/2016   0.248        1.326

有很多NA值,但也有很多&#34; true&#34;值。也许那些NAs不知不觉地抛弃了它?这是图表(可能与您的数据不完全相同)。如您所见,Global_horizo​​n_irradiance结束于400: enter image description here

这是我的代码:

ggplot(irradiance, aes(x=lambda)) + geom_line(aes(y=Global_horizn_irradiance), color="red") + geom_line(aes(y=Local_irrad), color="blue")

2 个答案:

答案 0 :(得分:1)

geom_line忽略NA个值,因此红色线的x轴映射被破坏。如果您希望它们匹配,则可能必须改为使用geom_point

> ggplot(irradiance, aes(x=lambda)) + 
+ geom_point(aes(y=Global_horizn_irradiance), color="red") + 
+ geom_point(aes(y=Local_irrad), color="blue")
Warning message:
Removed 3 rows containing missing values (geom_point). #notice that your original call doesn't generate this warning

答案 1 :(得分:1)

正如@StéphaneLaurent评论的那样,geom_line定义了NA分解细分的线段。您可以按如下方式手动删除NA的行,以提供连续的图表:

ggplot(irradiance, aes(x=lambda)) + geom_line(data=subset(irradiance, !is.na(Global_horizn_irradiance)), aes(y=Global_horizn_irradiance), color="red") + geom_line(aes(y=Local_irrad), color="blue")