ggplot条形图限制修复

时间:2020-07-30 01:00:37

标签: r ggplot2

我正在尝试固定条形图的限制,以使水平条形图不会越过绘图区域。我可以使用limits=c(0,3000000)手动设置限制,但是我想有一种方法可以使其自动扩展。代码

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))

我认为:

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

赞赏有关此修复程序的任何建议。

1 个答案:

答案 0 :(得分:3)

我认为将代码分成几部分会更容易阅读运行代码。

我们可以使用layer_data从ggplot对象获取信息,并从中计算出最大值。根据您的示例,我还建议您将最大值乘以1.7以包含文本。

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