我有一个6列5行的矩阵。第一列是week index和rest是百分比变化。它可能看起来像这样:
我想在R中创建一个美观的线状图,使用ggplot或dygraph,带有标记轴和彩色线条(用于第2到6列)
任何扩展的帮助都将不胜感激。
发布于 2015-06-19 16:17:33
您对“美观的”图形的要求有点模糊,但这里是如何使用ggplot2生成一个带标签的彩色图形。
首先,模拟一些数据以符合您描述的格式:
set.seed(2015)
df = data.frame(week = 1:5,
pct1 = sample(1:100, 5),
pct2 = sample(1:100, 5),
pct3 = sample(1:100, 5),
pct4 = sample(1:100, 5),
pct5 = sample(1:100, 5))
df
week pct1 pct2 pct3 pct4 pct5
1 1 7 36 71 89 70
2 2 84 50 39 27 41
3 3 30 8 4 8 21
4 4 4 64 40 79 65
5 5 14 99 72 37 71
要使用ggplot2生成所需的绘图,应将数据转换为“长”格式。我使用tidyr
包中的函数gather
(您也可以使用reshape2
包中等效的melt
函数)。
library(tidyr)
library(ggplot2)
# Gather the data.frame to long format
df_gathered = gather(df, pct_type, pct_values, pct1:pct5)
head(df_gathered)
week pct_type pct_values
1 1 pct1 7
2 2 pct1 84
3 3 pct1 30
4 4 pct1 4
5 5 pct1 14
6 1 pct2 36
现在,您可以通过使用pct_type
变量进行着色来轻松生成绘图。
ggplot(data = df_gathered, aes(x = week, y = pct_values, colour = pct_type)) +
geom_point() + geom_line(size = 1) + xlab("Week index") + ylab("Whatever (%)")
注意:如果变量week
是一个因子(我假设它是一个数字,因为您将其称为“周索引”),您还需要告诉ggplot
按pct_type
对数据进行分组,如下所示:
ggplot(data = df_gathered, aes(x = week, y = pct_values,
colour = pct_type, group = pct_type)) +
geom_point() + geom_line(size = 1) + xlab("Week index") + ylab("Whatever (%)")
https://stackoverflow.com/questions/30932290
复制相似问题