使用 ggplot2 在 R 中绘制散点图:

Scatterplot in R with ggplot2:

我有以下数据集。

> y
                  DF           GE
2006-12-21 -0.0004659447 -0.009960682
2006-12-22 -0.0009323238 -0.005295208
2006-12-26 -0.0032661785  0.003726377
2006-12-27  0.0042131332  0.002121453
2006-12-28 -0.0009323238 -0.008203228
2006-12-29 -0.0135313109 -0.007203842

我加固后就变成这样了

> fortify(y, melt=TRUE)
    Index     Series         Value
1  2006-12-21     DF -0.0004659447
2  2006-12-22     DF -0.0009323238
3  2006-12-26     DF -0.0032661785
4  2006-12-27     DF  0.0042131332
5  2006-12-28     DF -0.0009323238
6  2006-12-29     DF -0.0135313109
7  2006-12-21     GE -0.0099606815
8  2006-12-22     GE -0.0052952078
9  2006-12-26     GE  0.0037263774
10 2006-12-27     GE  0.0021214532
11 2006-12-28     GE -0.0082032284
12 2006-12-29     GE -0.0072038420

现在我想运行 ggplot2 中的散点图。目前,我使用的功能如下。

x <- fortify(x, melt=TRUE)
ggplot(data=x) +
geom_point(size=10, aes(x=Series, y=Value, colour=Index))

但我真正想要的是一个散点图,其中 DF 和 GE 的值作为 X 和 Y 轴上的坐标,日期用颜色显示。

我根本不知道如何修改数据结构来实现这一点。

你的意思是这样的吗?

library(tidyverse)
df %>%
    rownames_to_column("date") %>%
    mutate(date = as.Date(date)) %>%
    ggplot(aes(x = DF, y = GE)) +
    geom_point(aes(colour = date))


示例数据

df <- read.table(text =
    "                 DF           GE
2006-12-21 -0.0004659447 -0.009960682
2006-12-22 -0.0009323238 -0.005295208
2006-12-26 -0.0032661785  0.003726377
2006-12-27  0.0042131332  0.002121453
2006-12-28 -0.0009323238 -0.008203228
2006-12-29 -0.0135313109 -0.007203842", header = T)

我不会使用 fortify()。我会按原样保留您的数据并执行以下操作:

library(tidyverse)

y %>%
rownames_to_column() %>%   
ggplot(aes(x = DF, y = GE, color = index) + 
geom_point()