-3

I want to create an histogram in R like the one below. It should catch a dataframe with the selling number of that specific car on that specific year. So the data is formatted like: multiple columns (different cars) and multiple rows (multiple years). It should select 2 specific years from the rows (2001 and 2019) and show an histogram with the format below. How can I achieve this in R?

My code is:

table <- read_excel("sells.xlsx", sheet = "sheet", range = "A9:AI34")

View(table)

data <- table %>% select(Years, 'mercedes', 'nissan', 'volvo')%>% gather(key = "cars", value = "Total", -Years)
 

enter image description here

bgly
  • 157
  • 8
  • 1
    That looks like a bar chart, not a histogram. A histogram shows the distribution of a continuous variable. That said, what have you tried? There are lots of tutorials available on how to make a chart—that seems like a better place to start than by posting a very general question – camille Dec 28 '21 at 16:29

1 Answers1

0

I assume you have something like this

df <- tibble(
  years = c(2001, 2019) %>% 
     factor(),
  nissan = c(10, 15),
  volvo = c(12, 18),
  mercedes = c(19, 21)
)

Then with ggplot you can do the following

df %>%
  pivot_longer(2:4, names_to="sells") %>%
  ggplot(aes(x = years, fill = sells, y = value)) +
  geom_bar(stat = "identity", position = "dodge2")

Which renders

enter image description here

Also, pivot_longer() is recommended instead of gather()

Martin
  • 307
  • 1
  • 10