Bharat
Bharat

Reputation: 2469

Stacked Bar Plot for one quantitative and one categorical variable

I have a data-frame as follows:

core_depth    formation_name
5668           name5
5739           name2
5791           name7
5841           name4
5856           name1
5876           name3
5882           name6

core_depth column represents the depth of the rock and formation_name is the name given to the rock formation by the geologists. I have scrambled the names to protect the data, but the idea is that these are unique names as in a character vector in R.

I need to draw a one-column stacked bar chart where only vertical scale is important. It starts at the first core_depth (5668) at the top and ends at the core-depth (5882) at the bottom. Each stack in the bar chart shows the 'proportion' of the depth corresponding to the name. I do not need the legend since the stacked bar itself serves as a depth and formation marker for other scatter plots. I can use either ggplot2 or plotly. Please advise or better, give sample code.

Upvotes: 0

Views: 570

Answers (1)

Mist
Mist

Reputation: 1948

Does this help:

df <- read.table(text = "core_depth    formation_name
                 5668           name5
                 5739           name2
                 5791           name7
                 5841           name4
                 5856           name1
                 5876           name3
                 5882           name6", stringsAsFactors = FALSE, header = TRUE)

library(dplyr)
library(ggplot2)

df <- df %>% 
  arrange(core_depth)

df$lag <- lag(df$core_depth)

df$abs <- df$core_depth - df$lag
df$abs[1] <- 0

ggplot(df) +
  geom_bar(aes(x = rep(0, nrow(df)),
               y = abs,
               fill = formation_name),
           stat = "identity")

enter image description here

Upvotes: 0

Related Questions