实际使用ggplot2画柱状体时,遇到x轴排序问题。本文描述问题及其解决过程。
data(tips, package = "reshape2")
library(tidyverse)
library(scales) # for percentage scales
tips %>% count(day) %>%
mutate(perc = n / nrow(tips)) -> tips2
ggplot(tips2, aes(x = day, y = perc)) + geom_bar(stat = "identity")
图形画出来了,但x轴的顺序不对。原来ggplot2的排序有一定规则:
- 如果是factor类型,则使用factor的level属性作为排序依据
- 如果是character类型,则按照字母顺序
显然上面因为days是字符串,默认按照字母顺序。下面我们修改days为factor类型。
tips2$day <- factor(tips2$day,levels = c("Thur", "Fri", "Sat", "Sun"))
ggplot(tips2, aes(x = day, y = perc)) + geom_bar(stat = "identity")
有时我们并不满足x轴按照factor排序,假设需要按照频率排序,最频繁的序列排在最前面,实现方式如下:
ggplot(tips2, aes(x = reorder(day, -perc), y = perc)) + geom_bar(stat = "identity")
注意,上面代码中的负号表示降序。
本文参考链接:https://blog.csdn.net/neweastsun/article/details/121801992