Hos*_*ein 3 r ggplot2 geom-col
我正在使用ggplot绘制条形图。如何更改条形图中组的顺序?在以下示例中,我希望将 type=1984 作为第一个条形堆栈,然后将 type=1985 放在 1984 之上,依此类推。
series <- data.frame(
time = c(rep(1, 4),rep(2, 4), rep(3, 4), rep(4, 4)),
type = c(1984:1987),
value = rpois(16, 10)
)
ggplot(series, aes(time, value, group = type)) +
geom_col(aes(fill= type))
Run Code Online (Sandbox Code Playgroud)
使用更改顺序series<- series[order(series$type, decreasing=T),]只会更改图例中的顺序,而不是绘图中的顺序。
从 ggplot2 版本 2.2.1 开始,您无需重新排序数据框的行来确定图中堆栈的顺序。
因此,纯 ggplot 方法(作为 tmfmnk 答案的替代方法)将是:
library(ggplot2)
series %>%
ggplot(aes(time, value, group=factor(type, levels=1987:1984)))+
geom_col(aes(fill= factor(type)))+
guides(fill=guide_legend(title="type"))
Run Code Online (Sandbox Code Playgroud)
作为一种很好的做法,我建议在将变量绘制type为分类变量时使用因子。
结果:
使用desc()自dplyr:
ggplot(series, aes(time, value, group = desc(type))) +
geom_col(aes(fill= type))
Run Code Online (Sandbox Code Playgroud)