0

This is what I wantHow to make R side by side two column histogram (above) which I am able to do in python (image taken from here) and all the answers I have found for R get this resultimage taken from here

I tried searching for answers on stackoverflow and just google in general but no one seemed to be able to tell me how to make the histogram I want.

luisa
  • 15
  • 1
  • 5

2 Answers2

0

You have to set position = 'dodge' in the geom_bar command plot bars side by side. You can use something like this:

library(ggplot2)
library(reshape2)

variable_x <- c(5,47,31,9,37,10,35,28,16,29,14,34)
variable_y <- c(1,2,3,4,5,6,7,8,9,10,11,12)
variable_z <- c(1,2,3,4,5,6,7,8,9,10,11,12)

df <- data.frame(variable_x, variable_y, variable_z)
df <- melt(df, id.vars='variable_z')

df %>%
  ggplot(aes(x=variable_z, y=value, fill=variable)) +
  geom_bar(stat='identity', position='dodge')

Output:

enter image description here

Quinten
  • 35,235
  • 5
  • 20
  • 53
0

Here is an example using the iris data set. First you have to bring the data in long format with pivot_longer

and then apply geom_histogram() with position= 'dodge'

library(tidyverse)

iris %>% 
  pivot_longer(
    c(Sepal.Length, Sepal.Width, Petal.Length)
  ) %>% 
  ggplot(aes(value, fill=name))+
  geom_histogram(position = "dodge")

enter image description here

TarJae
  • 72,363
  • 6
  • 19
  • 66