Search code examples
rhistogram

How to create a horizontal histogram to visualize numbers based on their corresponding rows in R


data <- c(-1.66, -0.02, -0.45, -0.31, -0.42, 0.13, -1.9, 0.39, 0.66, 0.47,
          -1.98, 0.15, 0.34, -0.01, -0.25, 0.34, 0.62, -0.25, -0.93, 2.22,
          1.04, -1.35, -0.31, 0.76, 0.98, 0.76, -0.05, 1.2, -0.33, 1.47,
          1.78, 0.51, 0.91, -3.97, -0.54, -1.35, -2.05, 0.6, 0.73, 1.48,
          -1.35, 0.21, -0.4, 0.9, 0, 1.46, 1.71, 0.73, -1.49, 0.69, -1.86)

df <- data.frame(time = data)

I want to create a horizontal histogram to represent numerical data, with each number being associated or linked to its respective row in a dataset . This means that each bar in the histogram would represent a specific number from the dataset. I would prefer R basic


Solution

  • I am not sure the plot below answers the question. It creates a dot plot first, saves the plot in p then extracts the dots stack position. It uses those positions to plot the row numbers instead of dots.

    data <- c(-1.66, -0.02, -0.45, -0.31, -0.42, 0.13, -1.9, 0.39, 0.66, 0.47,
              -1.98, 0.15, 0.34, -0.01, -0.25, 0.34, 0.62, -0.25, -0.93, 2.22,
              1.04, -1.35, -0.31, 0.76, 0.98, 0.76, -0.05, 1.2, -0.33, 1.47,
              1.78, 0.51, 0.91, -3.97, -0.54, -1.35, -2.05, 0.6, 0.73, 1.48,
              -1.35, 0.21, -0.4, 0.9, 0, 1.46, 1.71, 0.73, -1.49, 0.69, -1.86)
    
    df <- data.frame(time = data)
    
    library(ggplot2)
    
    p <- ggplot(df, aes(x = time)) + geom_dotplot()
    q <- ggplot_build(p)
    #> Bin width defaults to 1/30 of the range of the data. Pick better value with
    #> `binwidth`.
    x <- q$data[[1L]]$stackpos
    
    i <- order(df$time)
    df2 <- data.frame(x, y = df$time[i], row = row.names(df)[i])
    
    ggplot(df2, aes(x, y)) +
      geom_text(aes(label = row))
    

    Created on 2024-06-21 with reprex v2.1.0