How can I make a Frequency distribution bar plot in ggplot2?

前端 未结 2 842
南旧
南旧 2021-01-26 00:25

Sample of the dataset.

nq
0.140843018
0.152855833
0.193245919
0.156860105
0.171658019
0.186281942
0.290739146
0.162779517
0.164694042
0.171658019
0.195866609
0.1         


        
2条回答
  •  滥情空心
    2021-01-26 00:58

    Would that work for you?

    nq <- read.table(text = "
    0.140843018
    0.152855833
    0.193245919
    0.156860105
    0.171658019
    0.186281942
    0.290739146
    0.162779517
    0.164694042
    0.171658019
    0.195866609
    0.166967913
    0.136841748
    0.108907644
    0.264136384
    0.356655651
    0.250508305", header = F) # Your data
    
    nq$V2 <- cut(nq$V1, 5, include.lowest = T)
    nq2 <- aggregate(V1 ~ V2, nq, length)
    nq2$V3 <- nq2$V1/sum(nq2$V1)
    library(ggplot2)
    ggplot() + geom_bar(data = nq2, aes(V2, V1), stat = "identity", width=1, fill = "white", col = "black", size = 2) + 
      geom_text(vjust=1, fontface="bold", data = nq2, aes(label = paste(sprintf("%.1f", V3*100), "%", sep=""), x = V2,  y = V1 + 0.4), size = 5) + 
      theme_bw() +
      scale_x_discrete(expand = c(0,0), labels = sprintf("%.3f",seq(min(nq$V1), max(nq$V1), by = max(nq$V1)/6))) +
      ylab("No. of Cases") + xlab("") +
      scale_y_continuous(expand = c(0,0)) +
      theme(
        axis.title.y = element_text(size = 20, face = "bold", angle = 0), 
        panel.grid.major = element_blank() ,
        panel.grid.minor = element_blank() ,
        panel.border = element_blank() ,
        panel.background = element_blank(),
        axis.line = element_line(color = 'black', size = 2),
        axis.text.x = element_text(face="bold"),
        axis.text.y = element_text(face="bold")
        ) 
    

    enter image description here

提交回复
热议问题