0

I am trying to create something like this:

enter image description here

Insired by this question i tried the following, but i does not work:

claims_freq  <- c(0.1,0.3,0.2,0.7,0.1)
claims_sev <- c(10000, 12000, 14000, 16000, 1600)
year <- c(2015, 2016, 2017, 2018, 2019)
data <- cbind(claims_freq, claims_sev, year)
data <- as.data.table(data)

twoord.stackplot(lx=data$year, rx=data$year, 
                 ldata=cbind(data$claims_freq),
                 rdata=cbind(data$claims_sev), 
                 lcol=c("black"),
                 rcol=c("black"), 
                 ltype=c("l"),
                 rtype=c("bar"), 
                 lylab="freq", rylab="sev", 
                 xlab="year",
                 main="Freq/Sev 2015-2020",
                 border="grey80")

is it possible to do this in ggplot?

Nneka
  • 1,764
  • 2
  • 15
  • 39
  • On the example plot you gave there is a column plot, not histogram. Do you want to make column & line plot? – RaV Mar 27 '20 at 13:08

1 Answers1

1

Try:

#It has to be in data.frame format
data <- data.frame(year, claims_sev, claims_freq)

#column plot + line plot
ggplot(data, aes(year)) +
  geom_col(aes(y = claims_sev), fill = "#D17F7D") +
#adding line plot - x times the value (e.g. 30 000)
  geom_line(aes(y = claims_freq*30000), color = "#227BC4") +
#adding second axis + dividing main axis by x
  scale_y_continuous(sec.axis = sec_axis(~./30000))
#you can use `labels()` and `theme()` for further adjustments

Result: Column & line plot

RaV
  • 617
  • 1
  • 5
  • 11
  • yes, this works...however, how to deal with very different scales on the x-axis? Note I have edited the question accordingly – Nneka Mar 27 '20 at 13:14
  • @Danka just manipulate multiplications in `geom_line()` and `sec_axis()`. You can do it manually, or with some simple equation of claims_freq and claims_seq. I've adjusted my solution to new data. – RaV Mar 27 '20 at 13:23