Graph of trends in ggplot2

Asked

Viewed 88 times

2

How to play the chart below using ggplot2?

inserir a descrição da imagem aqui

Data and ggplot2 code I’m trying

ano<-c("2009", "2011", "2013","2014","2016","2017","2018","2019")
mean.est<-c(0.975, 1.204, 1.504, 1.741, 1.77,2.166,2.378,2.564)
lower<-c(0.041, 0.771, 1.114, 1.374, 1.419,1.804,1.993, 2.12)
upper<-c(1.876, 1.669, 1.867, 2.081, 2.162, 2.499,2.745, 3.021)
mean.obs<-c(2.659, 1.155, 1.56, 1.848, 1.56,2.253,2.407,2.541)
graf<-data.frame(ano,mean.est, lower, upper, mean.obs)

ggplot(graf,aes(x=ano, y=mean.est))+
    geom_pointrange(fill="black", size= .4, ymin=graf$lower, ymax=graf$upper)+ 
    ylim(0, 3)+
    ylab("Número de abates (log)")+
    xlab("Ano")

1 answer

4


This type of problem usually has to do with data remodeling. The format should be long and the data in broad format. See est post do SO em inglês on how to reshape data from wide format to long format.

Note also that to place the caption inside the chart, the coordinates in

legend.position = c(0.5, 0.1)

are on the scale [0, 1] for each axle. The value 0.5 means the middle of the axle and the value 0.1 one-tenth of the start of the axle.

library(dplyr)
library(ggplot2)

Anos <- seq(min(as.integer(graf$ano)), max(as.integer(graf$ano)), by = 2)

graf %>%
  mutate(ano = as.integer(ano)) %>%
  tidyr::pivot_longer(
    cols = starts_with('mean'),
    names_to = 'group',
    values_to = 'mean'
  ) %>% 
  ggplot(aes(x = ano, y = mean)) +
  geom_line(aes(color = group)) +
  geom_ribbon(aes(ymin = lower, ymax = upper), alpha = 0.2, show.legend = FALSE) +
  scale_color_manual(values = c(mean.est = 'blue', mean.obs = 'black')) +
  scale_x_continuous(breaks = Anos, labels = Anos) +
  ylab("Número de abates (log)") +
  xlab("Ano") +
  theme_bw() +
  theme(legend.position = c(0.5, 0.1),
        legend.title = element_blank(),
        legend.direction = 'horizontal',
        strip.text.x = element_blank(),
        strip.background = element_rect(colour = "white", fill = "white")
  )

inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.