使用 ggplot 与使用基本 R 函数时的图形结果不同?

dav*_*ave 2 graphing plot r data-analysis ggplot2

我正在为 R 中的一个项目创建一些简单的图表。使用 ggplot2 包时,我得到了意想不到的结果,因此我默认回到基本 R。在基本 R 中重新创建绘图时,我得到了正确的结果。现在我只是想知道为什么会产生不同的结果?

\n

最初,这是使用 ggplot 的代码和结果(这是不正确的):

\n
ggplot(KBUF, aes(x = TEMP, y = HGHT)) +\ngeom_line(aes(color = "Temperature"), size = 1) +\ngeom_line(aes(x = DEWP, color = "Dew Point"), size = 1) +\nscale_color_manual(values = c("blue", "red")) +\nlabs(x = "Temperature (\xc2\xb0C)", y = "Height")\n
Run Code Online (Sandbox Code Playgroud)\n

这是输出图

\n

我在 R 基础上绘制的正确图

\n

\n

有以下代码:

\n
plot(KNKX$TEMP, KNKX$HGHT, type = "l", col = "blue", xlab = "Temperature (\xc2\xb0C)", ylab = "Height")\n\nlines(KNKX$DEWP, KNKX$HGHT, col = "red")\n\nlegend("topright", legend = c("Temperature", "Dew Point"), col = c("blue", "red"), lty = 1)\n
Run Code Online (Sandbox Code Playgroud)\n

为什么它们不同?

\n

All*_*ron 5

geom_line获取所有 (x, y) 坐标并将它们从最小 x 值到最大 x 值排序,然后通过这些点绘制一条线。如果您想绘制一条按点出现顺序穿过点的线,则需要使用geom_path,而不是geom_line

例如,假设我有一个数据框,其中圆的坐标按逆时针顺序排列:

df <- data.frame(x = sin(pi * seq(-1, 1, 0.01)),
                 y = cos(pi * seq(-1, 1, 0.01)))
Run Code Online (Sandbox Code Playgroud)

如果我用 绘制它geom_line,我会变得一团糟,因为该线根据 x 值连接所有点:

library(ggplot2)

ggplot(df, aes(x, y)) + geom_line()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

如果我想保留顺序,我只需使用geom_path而不是geom_line

ggplot(df, aes(x, y)) + geom_path()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述