时间序列的ggplot条形图
ggplot bar chart for time series
我正在阅读 Hadley Wickham 撰写的关于 ggplot 的书,但我无法在条形图中绘制某些权重随时间的变化。这是示例数据:
dates <- c("20040101","20050101","20060101")
dates.f <- strptime(dates,format="%Y%m%d")
m <- rbind(c(0.2,0.5,0.15,0.1,0.05),c(0.5,0.1,0.1,0.2,0.1),c(0.2,0.2,0.2,0.2,0.2))
m <- cbind(dates.f,as.data.frame(m))
这个 data.frame 在第一列中有日期,每一行都有相应的权重。我想使用 "fill" 参数在条形图中绘制每年的权重。
我可以使用以下方法将权重绘制为条形图:
p <- ggplot(m,aes(dates.f))
p+geom_bar()
然而,这并不是我想要的。我想在每个栏中看到每个权重的贡献。而且,我不明白为什么我在x轴上有奇怪的格式,即为什么显示“2004-07”和“2005-07”。
感谢您的帮助
希望这就是您要找的:
ggplot2
需要长格式的数据。
require(reshape2)
m_molten <- melt(m, "dates.f")
绘图本身由
完成
ggplot(m_molten, aes(x=dates.f, y=value, fill=variable)) +
geom_bar(stat="identity")
如果需要,您可以将 position="dodge"
添加到 geom_bar
然后并排。
编辑
如果您只想按年休假:将 m_molten$dates.f
转换为日期。
require(scales)
m_molten$dates.f <- as.Date(m_molten$dates.f)
ggplot(m_molten, aes(x=dates.f, y=value, fill=variable)) +
geom_bar(stat="identity") +
scale_x_date(labels = date_format("%y"), breaks = date_breaks("year"))
P.S。:请参阅 http://vita.had.co.nz/papers/tidy-data.pdf 了解 Hadley 的整洁数据哲学。
要创建您需要的图,您必须将数据从 "wide" 重塑为 "tall"。有很多方法可以做到这一点,包括 base R 中的 reshape()
函数(不推荐)、reshape2
和 tidyr
.
在 tidyr
包中,您有两个函数来重塑数据,gather()
和 spread()
。
函数gather()
从宽变高。在这种情况下,您必须收集列 V1:V5
.
试试这个:
library("tidyr")
tidy_m <- gather(m, var, value, V1:V5)
ggplot(tidy_m,aes(x = dates.f, y=value, fill=var)) +
geom_bar(stat="identity")
我正在阅读 Hadley Wickham 撰写的关于 ggplot 的书,但我无法在条形图中绘制某些权重随时间的变化。这是示例数据:
dates <- c("20040101","20050101","20060101")
dates.f <- strptime(dates,format="%Y%m%d")
m <- rbind(c(0.2,0.5,0.15,0.1,0.05),c(0.5,0.1,0.1,0.2,0.1),c(0.2,0.2,0.2,0.2,0.2))
m <- cbind(dates.f,as.data.frame(m))
这个 data.frame 在第一列中有日期,每一行都有相应的权重。我想使用 "fill" 参数在条形图中绘制每年的权重。
我可以使用以下方法将权重绘制为条形图:
p <- ggplot(m,aes(dates.f))
p+geom_bar()
然而,这并不是我想要的。我想在每个栏中看到每个权重的贡献。而且,我不明白为什么我在x轴上有奇怪的格式,即为什么显示“2004-07”和“2005-07”。
感谢您的帮助
希望这就是您要找的:
ggplot2
需要长格式的数据。
require(reshape2)
m_molten <- melt(m, "dates.f")
绘图本身由
完成ggplot(m_molten, aes(x=dates.f, y=value, fill=variable)) +
geom_bar(stat="identity")
如果需要,您可以将 position="dodge"
添加到 geom_bar
然后并排。
编辑
如果您只想按年休假:将 m_molten$dates.f
转换为日期。
require(scales)
m_molten$dates.f <- as.Date(m_molten$dates.f)
ggplot(m_molten, aes(x=dates.f, y=value, fill=variable)) +
geom_bar(stat="identity") +
scale_x_date(labels = date_format("%y"), breaks = date_breaks("year"))
P.S。:请参阅 http://vita.had.co.nz/papers/tidy-data.pdf 了解 Hadley 的整洁数据哲学。
要创建您需要的图,您必须将数据从 "wide" 重塑为 "tall"。有很多方法可以做到这一点,包括 base R 中的 reshape()
函数(不推荐)、reshape2
和 tidyr
.
在 tidyr
包中,您有两个函数来重塑数据,gather()
和 spread()
。
函数gather()
从宽变高。在这种情况下,您必须收集列 V1:V5
.
试试这个:
library("tidyr")
tidy_m <- gather(m, var, value, V1:V5)
ggplot(tidy_m,aes(x = dates.f, y=value, fill=var)) +
geom_bar(stat="identity")