Starter
Starter

Reputation: 9

how can i plot a line on bar chart in R

H <- c(1,2,4,1,0,0,3,1,3)
M <- c("one","two","three","four","five")
barplot(H,names.arg=M,xlab="number",ylab="random",col="blue",
    main="bar chart",border="blue")

I want to add line on the bar chart , i don't know how to do it

like the one in blue

image

Upvotes: 1

Views: 2886

Answers (2)

Rui Barradas
Rui Barradas

Reputation: 76402

The graph in the question can be made with code following the lines of:

1. Table the x vector.

tbl <- table(H)
df1 <- as.data.frame(tbl)

2. With package ggplot2, built-in ways of fitting a line can be used.

ggplot(df1, aes(as.integer(Var1), Freq)) +
  geom_bar(stat = "identity", fill = "red", alpha = 0.5) +
  geom_smooth(method = stats::loess, 
              formula = y ~ x, 
              color = "blue", fill = "blue",
              alpha = 0.5)

enter image description here

Test data creation code.

set.seed(2020)
f <- function(x) sin(x)^2*exp(x)
p <- f(seq(0, 2.5, by = 0.05))
p <- p/sum(p)
H <- sample(51, size = 1e3, prob = p, replace = TRUE)

Edit

Here is a new graph, with the new data posted in comment. The data is at the end of this answer.

library(ggplot2)
library(scales)

Mdate <- as.Date(paste0(M, "/2020"), format = "%d/%m/%Y")
df1 <- data.frame(H, M = Mdate)


ggplot(df1, aes(M, H)) +
  geom_bar(stat = "identity", fill = "red", alpha = 0.5) +
  geom_smooth(method = stats::loess, 
              formula = y ~ x, 
              color = "blue", fill = "blue", alpha = 0.25,
              level = 0.5, span = 0.1) +
  scale_x_date(labels = date_format("%d/%m"))

enter image description here

New data

H <- c(1,2,4,1,0,0,3,1,3,3, 6,238,0,
       58,17,64,38,3,10,8, 10,11,13,
       7,25,11,12,13,28,44)  
M <- c("29/02","01/03","02/03","03/03",
       "04/03","05/03","06/03","07/03",
       "08/03", "09/03","10/03","11/03",
       "12/03","13/03","14/03","15/03",
       "16/03", "17/03","18/03","19/03",
       "20/03","21/03","22/03","23/03",
       "24/03", "25/03","26/03","27/03",
       "28/03","29/03")

Upvotes: 0

Edward
Edward

Reputation: 18653

Maybe you want this?

hist(H, breaks=-1:4, freq=FALSE, xaxt="n")
axis(side=1, at=seq(-0.5, 3.5), labels=M)
lines(density(H))

enter image description here

Upvotes: 2

Related Questions