打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Histogram and density plot

Problem

You want to make a histogram or density plot.

Solution

Some sample data: these two vectors contain 200 data points each:

set.seed(1234)rating <- rnorm(200)head(rating)#> [1] -1.2070657 0.2774292 1.0844412 -2.3456977 0.4291247 0.5060559rating2 <- rnorm(200, mean=.8)head(rating2)#> [1] 1.2852268 1.4967688 0.9855139 1.5007335 1.1116810 1.5604624

When plotting multiple groups of data, some graphing routines require a data frame with one column for the grouping variable and one for the measure variable.

# Make a column to indicate which group each value is incond <- factor( rep(c('A','B'), each=200) )data <- data.frame(cond, rating = c(rating,rating2))head(data)#>   cond     rating#> 1    A -1.2070657#> 2    A  0.2774292#> 3    A  1.0844412#> 4    A -2.3456977#> 5    A  0.4291247#> 6    A  0.5060559
# Histogramhist(rating)# Use 8 bins (this is only approximate - it places boundaries on nice round numbers) # Make it light blue #CCCCFF # Instead of showing count, make area sum to 1, (freq=FALSE)hist(rating, breaks=8, col='#CCCCFF', freq=FALSE)# Put breaks at every 0.6boundaries <- seq(-3, 3.6, by=.6)boundaries#> [1] -3.0 -2.4 -1.8 -1.2 -0.6 0.0 0.6 1.2 1.8 2.4 3.0 3.6hist(rating, breaks=boundaries)# Kernel density plotplot(density(rating))

Multiple groups with kernel density plots.

This code is from: http://onertipaday.blogspot.com/2007/09/plotting-two-or-more-overlapping.html

plot.multi.dens <- function(s){
    junk.x = NULL
    junk.y = NULL
    for(i in 1:length(s)) {
        junk.x = c(junk.x, density(s[[i]])$x)
        junk.y = c(junk.y, density(s[[i]])$y)
    }
    xr <- range(junk.x)
    yr <- range(junk.y)
    plot(density(s[[1]]), xlim = xr, ylim = yr, main = '')
    for(i in 1:length(s)) {
        lines(density(s[[i]]), xlim = xr, ylim = yr, col = i)
    }}# the input of the following function MUST be a numeric listplot.multi.dens( list(rating, rating2))

The sm package also includes a way of doing multiple density plots. The data must be in a data frame.

library(sm)sm.density.compare(data$rating, data$cond)# Add a legend (the color numbers start from 2 and go up)legend('topright', levels(data$cond), fill=2+(0:nlevels(data$cond)))

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Histogram with density curves in R | R CHARTS
5.4 Graphical Methods, Histograms and Scatter Diagrams
如何将多个ggplot图组合成可公开的图
The Pirate Plot (2.0) – The RDI plotting choice of R pirates
ggplot2|从0开始绘制直方图
如何使用R语言在SAP Analytics Cloud里绘制各种统计图表
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服