0

The data is

y0 y1
M 100 200
F 50 250

How to plot the histogram like this? Note that M and F do not block each other, so this is not the case in How to plot two histograms together in R. Thanks in advance.

his

MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • 2
    Please provide the data with `dput`. – Mossa Jun 02 '22 at 12:43
  • 1
    How exactly is your data stored? Is that a data.frame? It's better to share data in a [reproducible format](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) such as a `dput()`. Also, these would not be considered histograms. Histograms are a way to estimate the density function for a continuous random variable. What you've shown is just a stacked bar chart. – MrFlick Jun 02 '22 at 12:44
  • 2
    This is not a histogram, this is a barplot – Yacine Hajji Jun 02 '22 at 12:44

3 Answers3

0

Here's a straight solution:

library(tidyverse)
my_df <- tribble(~ sex, ~ y0, ~ y1,
                 "M", 100, 200,
                 "F", 50, 250)
my_df %>% 
  pivot_longer(starts_with("y")) %>% 
  ggplot(aes(name, value, fill = sex)) + 
  geom_col(position = "stack")
Mossa
  • 1,656
  • 12
  • 16
0

If your data is like df below:

library(tidyverse)

df <- tibble::tribble(
  ~V1,  ~y0,  ~y1,
  "M", 100L, 200L,
  "F",  50L, 250L
)

df %>% 
  pivot_longer(-V1) %>% 
  ggplot(aes(x = name, y = value, fill = V1)) +
  geom_bar(stat = 'identity')

Which gives:

enter image description here

Matt
  • 7,255
  • 2
  • 12
  • 34
0

First, convert your data to long format with pivot_longer().

library(ggplot2)
library(tidyr)

df_long <- pivot_longer(df, cols = c("y0","y1"))

ggplot(data = df_long) +
  geom_col(aes(x = name, y = value, fill = sex)) +
  scale_fill_manual(values = c("M" = "blue", "F" = "darkorange")) +
  theme(legend.position = "bottom")
   

enter image description here data:

df <- data.frame(sex = c("M","F"),
           y0 = c(100,50),
           y1 = c(200,250))
Skaqqs
  • 4,010
  • 1
  • 7
  • 21
  • Thank you, but how can I modify name to something like 'count' in – Patrick Star Jun 02 '22 at 13:51
  • `pivot_longer()` created the field name `name`. Take a look at `View(df_long)` to confirm. To change the name in the data.frame you could use `names(df_long) <- c("sex", "count", "value")`, add the argument `names_to = "Count"` to `pivot_longer()`, or to change the x-axis label, you could use `+ xlab("Count")` in your ggplot function. – Skaqqs Jun 02 '22 at 14:14