gpt4 book ai didi

r - R中的堆积面积直方图

转载 作者:行者123 更新时间:2023-12-04 09:50:12 25 4
gpt4 key购买 nike

我在 Hadoop 集群上运行了一个 Pig 作业,该作业将一堆数据分解为 R 可以处理的内容,以进行群组分析。我有以下脚本,从倒数第二行开始,我有以下格式的数据:

> names(data)
[1] "VisitWeek" "ThingAge" "MyMetric"

VisitWeek 是一个日期。 ThingAge 和 MyMetric 是整数。

数据看起来像:
2010-02-07     49  12345

我到目前为止的脚本是:
# Load ggplot2 for charting 
library(ggplot2);

# Our file has headers - column names
data = read.table('weekly_cohorts.tsv',header=TRUE,sep="\t");

# Print the names
names(data)

# Convert to dates
data$VisitWeek = as.Date(data$VisitWeek)
data$ThingCreation = as.Date(data$ThingCreation)

# Fill in the age column
data$ThingAge = as.integer(data$VisitWeek - data$ThingCreation)

# Filter data to thing ages lt 10 weeks (70 days) + a sanity check for gt 0, and drop the creation week column
data = subset(data, data$ThingAge <= 70, c("VisitWeek","ThingAge","MyMetric"))
data = subset(data, data$ThingAge >= 0)

print(ggplot(data, aes(x=VisitWeek, y=MyMetric, fill=ThingAge)) + geom_area())

最后一行不起作用。我尝试了很多变体、条形图、直方图,但像往常一样,R 文档打败了我。

我希望它显示一个标准的 Excel 样式堆积面积图 - 每个 ThingAge 的一个时间序列在 x 轴上的几周内堆积,日期在 y 轴上。此类图表的示例如下: http://upload.wikimedia.org/wikipedia/commons/a/a1/Mk_Zuwanderer.png

我在这里阅读了文档: http://had.co.nz/ggplot2/geom_area.htmlhttp://had.co.nz/ggplot2/geom_histogram.html和这个博客 http://chartsgraphs.wordpress.com/2008/10/05/r-lattice-plot-beats-excel-stacked-area-trend-chart/但我不能让它为我工作。

我怎样才能做到这一点?

最佳答案

library(ggplot2)
set.seed(134)
df <- data.frame(
VisitWeek = rep(as.Date(seq(Sys.time(),length.out=5, by="1 day")),3),
ThingAge = rep(1:3, each=5),
MyMetric = sample(100, 15))

ggplot(df, aes(x=VisitWeek, y=MyMetric)) +
geom_area(aes(fill=factor(ThingAge)))

给我下面的图片。我怀疑您的问题在于正确指定区域图的填充映射: fill=factor(ThingAge)
enter image description here

关于r - R中的堆积面积直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2241290/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com