尝试在具有堆叠条形的图表中沿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")
我想按大小(即,红色,绿色和粉红色的总和)订购条形图(与MYshop中的苹果相同):basket4,basket1,basket3,basket2
我尝试过
ggplot(MYshop_long, aes(x = reorder(basket, MYshop$apples)), y = amount, fill = color)) +
geom_bar(stat = "identity", position = "stack")
但这不起作用。怎么做?
答案 0 :(得分:2)
这应该做
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")
答案 1 :(得分:1)