mik*_*sey 7 r histogram ggplot2
使用ggplot2,我想创建一个直方图,其中X以上的任何内容都被分组到最终的bin中.例如,如果我的大多数发行版都在100到200之间,并且我希望以10分为单位,那么我希望将200以上的任何内容分成"200+".
# create some fake data
id <- sample(1:100000, 10000, rep=T)
visits <- sample(1:1200,10000, rep=T)
#merge to create a dataframe
df <- data.frame(cbind(id,visits))
#plot the data
hist <- ggplot(df, aes(x=visits)) + geom_histogram(binwidth=50)
Run Code Online (Sandbox Code Playgroud)
如何限制X轴,同时仍然表示我想要限制的数据?
如果您想稍微捏造一下以解决 bin 标记问题,那么只需对数据进行子集化并在新的牺牲数据框中创建分箱值:
id <- sample(1:100000, 10000, rep=T)
visits <- sample(1:1200,10000, rep=T)
#merge to create a dataframe
df <- data.frame(cbind(id,visits))
#create sacrificical data frame
dfsac <- df
dfsac$visits[dfsac$visits > 200 ] <- 200
Run Code Online (Sandbox Code Playgroud)
然后使用breaks命令 inscale_x_continuous轻松定义您的 bin 标签:
ggplot(data=dfsac, aes(dfsac$visits)) +
geom_histogram(breaks=c(seq(0, 200, by=10)),
col="black",
fill="red") +
labs(x="Visits", y="Count")+
scale_x_continuous(limits=c(0, 200), breaks=c(seq(0, 200, by=10)), labels=c(seq(0,190, by=10), "200+"))
Run Code Online (Sandbox Code Playgroud)
也许你正在寻找以下breaks论点geom_histogram:
# create some fake data
id <- sample(1:100000, 10000, rep=T)
visits <- sample(1:1200,10000, rep=T)
#merge to create a dataframe
df <- data.frame(cbind(id,visits))
#plot the data
require(ggplot2)
ggplot(df, aes(x=visits)) +
geom_histogram(breaks=c(seq(0, 200, by=10), max(visits)), position = "identity") +
coord_cartesian(xlim=c(0,210))
Run Code Online (Sandbox Code Playgroud)
这看起来像这样(注意到假数据在这里看起来很糟糕,并且轴也需要调整以匹配断点):

编辑:
也许其他人可以在这里权衡:
# create breaks and labels
brks <- c(seq(0, 200, by=10), max(visits))
lbls <- c(as.character(seq(0, 190, by=10)), "200+", "")
# true
length(brks)==length(lbls)
# hmmm
ggplot(df, aes(x=visits)) +
geom_histogram(breaks=brks, position = "identity") +
coord_cartesian(xlim=c(0,220)) +
scale_x_continuous(labels=lbls)
Run Code Online (Sandbox Code Playgroud)
情节错误:
Error in scale_labels.continuous(scale) :
Breaks and labels are different lengths
Run Code Online (Sandbox Code Playgroud)
看起来像这样但是8个月前修复了.
| 归档时间: |
|
| 查看次数: |
4850 次 |
| 最近记录: |