我是ggplot的新手(在某种程度上是R)。我对使用ggplot创建的图表质量感到震惊,我正在尝试学习如何使用ggplot创建一个简单的多线图。
不幸的是,我还没有找到任何帮助我接近我想要做的教程:
我有一个包含以下数据的CSV文件:
id,f1,f2,f3,f4,f5,f6
30,0.841933670833,0.842101814883,0.842759547545,1.88961562347,1.99808377527,0.841933670833
40,1.47207692205,1.48713866811,1.48717177671,1.48729643008,1.48743226992,1.48713866811
50,0.823895293045,0.900091982861,0.900710334491,0.901274168324,0.901413662472,0.901413662472
我想绘图:
我是ggplot的新手,所以真的没有把文件读到R中。
如上所述,让我创建情节的任何帮助都将非常有教育意义,有助于减少ggplot的学习曲线。
答案 0 :(得分:3)
dat <- structure(list(id = c(30L, 40L, 50L), f1 = c(0.841933670833,
1.47207692205, 0.823895293045), f2 = c(0.842101814883, 1.48713866811,
0.900091982861), f3 = c(0.842759547545, 1.48717177671, 0.900710334491
), f4 = c(1.88961562347, 1.48729643008, 0.901274168324), f5 = c(1.99808377527,
1.48743226992, 0.901413662472), f6 = c(0.841933670833, 1.48713866811,
0.901413662472)), .Names = c("id", "f1", "f2", "f3", "f4", "f5",
"f6"), class = "data.frame", row.names = c(NA, -3L))
从这里我会使用melt
。请阅读?melt.data.frame
了解详情。但在一句话中,这将数据从“宽”格式转换为“长”格式。
library(reshape2)
dat.m <- melt(dat, id.vars='id')
> dat.m
id variable value
1 30 f1 0.8419337
2 40 f1 1.4720769
3 50 f1 0.8238953
4 30 f2 0.8421018
5 40 f2 1.4871387
6 50 f2 0.9000920
7 30 f3 0.8427595
8 40 f3 1.4871718
9 50 f3 0.9007103
10 30 f4 1.8896156
11 40 f4 1.4872964
12 50 f4 0.9012742
13 30 f5 1.9980838
14 40 f5 1.4874323
15 50 f5 0.9014137
16 30 f6 0.8419337
17 40 f6 1.4871387
18 50 f6 0.9014137
>
然后绘制你想要的情节:
ggplot(dat.m, aes(x=id, y=value, colour=variable)) +
geom_line() +
geom_point(data=dat.m[dat.m$variable=='f2',], cex=2)
aes
定义美学,例如x值,y值,颜色/颜色等。然后添加“图层”。在上一个示例中,我为ggplot()
部分中使用geom_line()
添加了一行,并在geom_point
添加了一个点,我只将它们放在f2
上变量。
下面,我添加了一条带geom_smooth()
的平滑线。有关这方面的更多信息,请参阅文档?geom_smooth
。
ggplot(dat.m, aes(x=id, y=value, colour=variable)) +
geom_smooth() +
geom_point(data=dat.m[dat.m$variable=='f2',], shape=3)
或所有人的形状。在这里,我塑造了ggplot()
的美学。通过将它们放在这里,它们适用于所有连续的层,而不是每次都必须指定它们。但是,我可以覆盖任何后续层中ggplot()
中提供的值:
ggplot(dat.m, aes(x=id, y=value, colour=variable, shape=variable)) +
geom_smooth() +
geom_point() +
geom_point(data=dat, aes(x=id, y=f2, color='red'), size=10, shape=2)
然而,一点ggplot
理解只需要时间。完成文档和ggplot2
网站上提供的一些示例。如果你的经历与我的相似,那么在与它斗争几天或几周后,它最终会点击。关于数据,如果您将数据分配给dat
,则代码不会更改。 dat <- read.csv(...)
。我不使用data
作为变量,因为它是内置函数。