1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| # Library library(ggplot2) library(dplyr) library(forcats)
# Dataset 1: one value per group data <- data.frame( name=c("north","south","south-east","north-west","south-west","north-east","west","east"), val=sample(seq(1,10), 8 ) )
# Reorder following the value of another column: p1 <- data %>% mutate(name = fct_reorder(name, val)) %>% ggplot( aes(x=name, y=val)) + geom_bar(stat="identity", fill="#f68060", alpha=.6, width=.4) + coord_flip() + xlab("") + theme_bw() # Reverse side p2 <- data %>% mutate(name = fct_reorder(name, desc(val))) %>% ggplot( aes(x=name, y=val)) + geom_bar(stat="identity", fill="#f68060", alpha=.6, width=.4) + coord_flip() + xlab("") + theme_bw()
# Using median p3 <- mpg %>% mutate(class = fct_reorder(class, hwy, .fun='median')) %>% ggplot( aes(x=reorder(class, hwy), y=hwy, fill=class)) + geom_boxplot() + geom_jitter(color="black", size=0.4, alpha=0.9) + xlab("class") + theme(legend.position="none") + xlab("") # Using number of observation per group p4 <- mpg %>% mutate(class = fct_reorder(class, hwy, .fun='length' )) %>% ggplot( aes(x=class, y=hwy, fill=class)) + stat_summary(fun.y=mean, geom="point", shape=20, size=6, color="red", fill="red") + geom_boxplot() + xlab("class") + theme(legend.position="none") + xlab("") + xlab("")
p5 <- data %>% arrange(val) %>% # First sort by val. This sort the dataframe but NOT the factor levels mutate(name=factor(name, levels=name)) %>% # This trick update the factor levels ggplot( aes(x=name, y=val)) + geom_segment( aes(xend=name, yend=0)) + geom_point( size=4, color="orange") + coord_flip() + theme_bw() + xlab("") p6 <- data %>% arrange(val) %>% mutate(name = factor(name, levels=c("north", "north-east", "east", "south-east", "south", "south-west", "west", "north-west"))) %>% ggplot( aes(x=name, y=val)) + geom_segment( aes(xend=name, yend=0)) + geom_point( size=4, color="orange") + theme_bw() + xlab("")
cowplot::plot_grid(p1, p2, p3, p4, p5, p6, ncol = 2, align = "hv", labels = LETTERS[1:6])
|