在ggplot2生成的堆叠条形图中定义条形顺序

问题描述

尝试在具有堆叠条形的图表中沿x轴从最小到最大设置条形顺序。

数据集:

MYshop = tibble(basket = c("basket1","basket2","basket3","basket4"),apples = c(10,100,50,6),red = c(2,5,10,4),green = c(1,30,1,1),pink = c(7,65,39,1))

我相信,要使用ggplot2生成堆叠的条形图,必须将数据集转换为长格式:

MYshop %>% 
select(basket,red,green,pink) %>% 
gather(color,amount,-basket) -> MYshop_long

堆积的条形图:

ggplot(MYshop_long,aes(x = basket,y = amount,fill = color)) + 
  geom_bar(stat = "identity",position = "stack")

sasa

我想按大小(即,红色,绿色和粉红色的总和)订购条形图(与MYshop中的苹果相同):basket4,basket1,basket3,basket2

我尝试过

ggplot(MYshop_long,aes(x = reorder(basket,MYshop$apples)),fill = color)) + 
      geom_bar(stat = "identity",position = "stack")

但这不起作用。怎么做?

解决方法

这应该做

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter,lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect,setdiff,setequal,union
library(tidyr)
library(ggplot2)

MYshop = tibble(basket = c("basket1","basket2","basket3","basket4"),apples = c(10,100,50,6),red = c(2,5,10,4),green = c(1,30,1,1),pink = c(7,65,39,1))

MYshop %>% 
  select(basket,red,green,pink) %>% 
  gather(color,amount,-basket) -> MYshop_long

ggplot(MYshop_long,aes(x = reorder(basket,amount),y = amount,fill = color)) + 
  geom_bar(stat = "identity",position = "stack")

enter image description here

,

我建议采用另一种方法,如您提到的,根据值的总和来格式化x轴中使用的变量。我添加了一些代码来进行汇总。之后,排序后的值可用于在var schedule = require('node-schedule'); schedule.scheduleJob('*/10 * * * *',function () { require('dns').resolve('www.google.com',function (err) { if (err) { } else { } }); });数据中重新定义变量basket

MYshop_long

输出:

enter image description here