Liondancer
Liondancer

Reputation: 16469

Creating histogram plot with 2 arrays

How can I create a histogram with this data in R?

f = c('0-5', '6-10', '11-15', '16-20', '> 20')
counts_arr = c(0, 8, 129, 127, 173)

Right now, counts_arr[0] is associated with f[0]

So I am trying to get f to be on the X axis and counts_arr values on the Y axis

Upvotes: 0

Views: 157

Answers (2)

Indrajeet Patil
Indrajeet Patil

Reputation: 4879

There is already a solution for this, but I had prepared something with ggplot2 that I am posting nonetheless.

library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 3.4.3
library(forcats)
#> Warning: package 'forcats' was built under R version 3.4.3

# dataframe provided
df <-
  base::cbind.data.frame(
    f = c('0-5', '6-10', '11-15', '16-20', '> 20'),
    counts_arr = c(0, 8, 129, 127, 173)
  )

# plot
ggplot2::ggplot(data = df, mapping = aes(x = forcats::fct_inorder(f), y = counts_arr)) +
  geom_bar(stat = "identity") +
  labs(x = "f", y = "count")

Created on 2018-02-10 by the reprex package (v0.1.1.9000).

Upvotes: 2

IceCreamToucan
IceCreamToucan

Reputation: 28685

barplot(counts_arr, names = f)

Upvotes: 4

Related Questions