ggplot bar chart limits fix

I am trying to fix the limits of a bar chart so the horizontal bar doesn't go over the plot area. I could set the limit manually using limits=c(0,3000000)but I guess there is a way to make it automatically scalable. The code

corona.conf <- read.csv("https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv",header = TRUE,check.names=FALSE)

corona.conf %>% .[,c(-1,-3,-4)] %>% melt(.,variable.name="day") %>% 
        group_by(`Country/Region`,day) %>% summarize(value=sum(value)) %>% 
        mutate(day=as.Date(day,format='%m/%d/%y')) %>% mutate(count=value-lag(value)) %>% 
        replace(is.na(.),0) %>% group_by(`Country/Region`) %>% summarize(count=sum(count)) %>% 
        top_n(20) %>% arrange(desc(count)) %>% ggplot(.,aes(x=reorder(`Country/Region`,count),y=count,fill=count)) + 
        geom_bar(stat = "identity") + coord_flip() + geom_text(aes(label=format(count,big.mark = ",")),hjust=-0.1,size=4) + 
        scale_y_continuous(expand = c(0,0))

I thought something like:

scale_y_continuous(expand = c(0,0),limits=c(0,max(count))

Appreciate any suggestions on the fix.

Upvotes: 3

Views: 155

Answers (1)

www
www

Reputation: 39154

I think it would be easier to read an run the code by splitting it into several parts.

We can use layer_data to get the information from a ggplot object, and the calculate the maximum from that. Based on your example, I would also suggest you multiply the maximum by 1.7 to include the text.

library(tidyverse)
library(data.table)

corona.conf <- read.csv("https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv",header = TRUE,check.names=FALSE)

dat <- corona.conf %>% .[,c(-1,-3,-4)] %>% melt(.,variable.name="day") %>% 
  group_by(`Country/Region`,day) %>% summarize(value=sum(value)) %>% 
  mutate(day=as.Date(day,format='%m/%d/%y')) %>% mutate(count=value-lag(value)) %>% 
  replace(is.na(.),0) %>% group_by(`Country/Region`) %>% summarize(count=sum(count)) %>% 
  top_n(20) %>% arrange(desc(count)) 

p <- ggplot(dat, aes(x=reorder(`Country/Region`,count),y=count,fill=count)) + 
  geom_bar(stat = "identity") + 
  coord_flip() + 
  geom_text(aes(label=format(count,big.mark = ",")),hjust=-0.1,size=4) 

p + 
  scale_y_continuous(expand = c(0,1), limits = c(0, max(layer_data(p)$y) * 1.7))

enter image description here

Upvotes: 3

Related Questions