Massive44
Massive44

Reputation: 29

Time series bar graph reordering

I have the following script I'm working on, I want to re order the bar graph in descending order by their values.

library(tidyverse)
library(lubridate)
library(ggplot2)

#df <- read_csv('dataframe.csv')
    
    df %>%
      mutate(date=mdy(date), year=year(date), year = year + (date >= mdy(paste0("10/01/", year))))%>%
      group_by(year) %>%
      summarize(avg = mean(flow)) -> df
    
    
    y <- df$avg
    x <- ymd(sprintf("%d-01-01",df$year))
    d <- data.frame(x = x, y = y)
    
    # interpolate values from zero to y and create corresponding number of x values
    vals <- lapply(d$y, function(y) seq(0, y, by = 0.1))
    y <- unlist(vals)
    mid <- rep(d$x, lengths(vals))
    d2 <- data.frame(x = mid - 100,
                     xend = mid + 100,
                     y = y,
                     yend = y)
    
    ggplot(data = d2, aes(x = x, xend = xend, y = y, yend = yend, color = y)) +
      geom_segment(size = 2)

Results enter image description here

I want to reorder the bars in descending order by values

The dataset can be found through the following link

https://drive.google.com/file/d/11PVub9avzMFhUz02cHfceGh9DrlVQDbD/view?usp=sharing

the output I'm looking for is like this. enter image description here

Kindly assist.

Upvotes: 0

Views: 148

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 389155

To arrange the data you need to adjust the factor levels. You could arrange the data based on avg column and change year to factor.

library(dplyr)
library(ggplot2)

df %>%
  arrange(desc(avg)) %>%
  mutate(year = factor(year, unique(year))) %>%
  ggplot() + aes(year, avg) + geom_col(aes(fill = 'red')) + guides(fill=FALSE)

enter image description here


Or :

df %>%
  arrange(desc(avg)) %>%
  mutate(year = factor(year, unique(year))) %>%
  ggplot() + aes(year, avg, fill = avg) + geom_col()

enter image description here

Upvotes: 2

Mohanasundaram
Mohanasundaram

Reputation: 2949

Try this:

library(scales)

#Custom Transform function
dttrans <- function(a, b, breaks = b$breaks, format = b$format) {
  a <- as.trans(a)
  b <- as.trans(b)
  
  name <- paste(a$name, b$name, sep = "-")
  
  trans <- function(x) a$trans(b$trans(x))
  inv <- function(x) b$inverse(a$inverse(x))
  
  trans_new(name, trans, inv, breaks, format = format)
  }

ggplot(data = d2, aes(x = x, xend = xend, y = y, yend = yend, color = y)) +
  geom_segment(size = 2) +
  scale_x_continuous(trans = dttrans("reverse", "date"))

Credits: Mikko Marttila

enter image description here

Upvotes: 1

Related Questions