使用geom_bar仅绘制最高和最低值

时间:2018-03-11 13:25:44

标签: r

我试图在条形图上绘制每个国家的GDP。国家名称在x轴上,GDP值在y上。然而,有很多国家,我希望条形图只显示前三大国内生产总值,以及最低三大国内生产总值,我希望可能会有一些点或其他东西来表明其他国家介于两者之间。我该怎么做?

2 个答案:

答案 0 :(得分:3)

以@ steveLangsford的解决方案为基础 - 以(可能)稍微更原则的方式做事

可能有更“整洁”的方式来完成这一部分:

  • 找到GDP类别的断点:
GDP_sorted <- sort(toydata$GDP)
GDP_breaks <- c(-Inf,GDP_sorted[hm_selected],
                 GDP_sorted[hm_rows-hm_selected],
                Inf)
  • 使用cut()来定义GDP类别,并按GDP订购国家:
toydata <- toydata %>%
  mutate(GDP_cat=cut(GDP,breaks=GDP_breaks,labels=
                       c("Lowest","Mid","Highest")),
         country=reorder(factor(country),GDP)) %>%
  filter(GDP_cat != "Mid") %>%
  droplevels()

使用刻面绘图(在面板之间添加一些额外空间以强调轴断裂):

ggplot(toydata,aes(x=country,y=GDP,fill=GDP_cat))+
  geom_bar(stat="identity")+
  theme_bw()+
  theme(legend.position="none",
    panel.spacing.x=grid::unit(5,"lines")
  )+xlab("")+
  scale_fill_brewer(palette="Dark2")+
  facet_wrap(~GDP_cat,scale="free_x")

enter image description here

答案 1 :(得分:2)

1)如果您提供玩具数据集,您将获得更快更好的答案 2)在你的情节上放置“点或点”可能会使数据可视化让人感到畏缩。你基本上建议x轴不连续,这是一个常见的事情要做,但明确排除在ggplot之外 (看这里: Using ggplot2, can I insert a break in the axis? 和这里: https://groups.google.com/forum/#!topic/ggplot2/jSrL_FnS8kc

但是,同样的讨论表明方面是解决问题的方法。一种方法可能是这样的:

library(tidyverse)
library(patchwork)
hm_rows <- 50
hm_selected <- 3
toydata <- data.frame(country=paste("Country",1:hm_rows) ,GDP=runif(hm_rows,0,5000))%>%
    arrange(desc(GDP))%>%
    filter(row_number()<=hm_selected | row_number()>(hm_rows-hm_selected))%>%droplevels

toydata$status <- rep(c("Highest","Lowest"),each=hm_selected)

ggplot(toydata%>%filter(status=="Highest"),aes(x=country,y=GDP))+
    geom_bar(stat="identity")+
    ggtitle("Highest")+
    ylim(c(0,max(toydata$GDP)))+
    ggplot(toydata%>%filter(status=="Lowest"),aes(x=country,y=GDP))+
    geom_bar(stat="identity")+
    ggtitle("Lowest")+
    ylim(c(0,max(toydata$GDP)))+
    theme(#possibly questionable, but tweaks the results closer to the single-graph requested:
        axis.text.y=element_blank(),
        axis.ticks=element_blank()
    )+ylab("")