Reputation: 583
When I run the code order of y-axis label is changed alphabetically, but I want to keep it as like as my coef
column of new.table
dataset. Here is my code:
library(ggplot2)
library(dplyr)
library(data.table)
coef<-c("<=40 years", "41-55 years", "56+ years", "Underweight", "Normal",
"Overweight", "Obese", "Uncontrolled", "Control", "Uncontrolled", "Control",
"< 5 years", "5-10 years", ">= 10 years", "Adherence", "Non-adherence")
or<-c(1,0.98, 1.16, 1.68, 1, 0.59, 0.71, 2.57, 1, 1.1, 1, 1, 2.03, 9.51, 1, 1.82)
ci_lb<-c(1, 0.41, 0.47, 0.25, 1, 0.33, 0.34, 1.3, 1, 0.63, 1, 1, 0.81, 3.85, 1, 1.07)
ci_ub<-c(1, 2.35, 2.87, 11.22, 1, 1.03, 1.48, 5.08, 1, 1.92, 1, 1, 5.09, 23.46, 1, 3.1)
term<-c("Age", "Age", "Age", "BMI", "BMI", "BMI", "BMI", "FBS", "FBS", "SBP", "SBP", "Duration", "Duration", "Duration", "Drug", "Drug")
is.reference<-rep(TRUE,16)
new.table<-data.frame(coef, or, ci_lb, ci_ub, term, is.reference)
p <- ggplot(new.table,
aes(x = or, xmin = ci_lb, xmax = ci_ub,
y = coef, color = term)) + coord_cartesian(xlim=c(0,25))+
geom_vline(xintercept = 1, linetype = "longdash") +
geom_errorbarh(height = 0.2) +
geom_point(size = 2, shape = 18) +
facet_grid(term~., scales = "free_y", space = "free_y")+
scale_alpha_identity()
Upvotes: 2
Views: 570
Reputation: 56004
To extend my comment a bit, we need to set factor order on coef and on term, then reverse y axis:
# factor
new.table$coef <- factor(new.table$coef, levels = unique(new.table$coef))
new.table$term <- factor(new.table$term, levels = unique(new.table$term))
ggplot(new.table,
aes(x = or, xmin = ci_lb, xmax = ci_ub,
y = coef, color = term)) + coord_cartesian(xlim=c(0,25))+
geom_vline(xintercept = 1, linetype = "longdash") +
geom_errorbarh(height = 0.2) +
geom_point(size = 2, shape = 18) +
facet_grid(term~., scales = "free_y", space = "free_y")+
scale_alpha_identity() +
# flip y-axis
scale_y_discrete(limits = rev)
Upvotes: 2