Reputation: 1057
I have a figure like below and I would like to change the order of colored lines from blue->green->red to r->g->b, so that it is the same as the legend's order. I have found several tutorials to change the order of legends, but I want to keep its order in this case (since they are 1, 2, and 3).
Here is the code to generate the data and figure.
population_num <- 100
population <- tibble(
gender = as.numeric(rbinom(population_num, 1, 0.5)),
age=rnorm(population_num, mean=50, sd=20),
score=rnorm(population_num, mean=80, sd=30),
setid=sample(c(1,2,3), size=population_num, replace=T)
)
temp <- population %>%
group_by(setid) %>%
do(model1 = tidy(lm(score ~ age, data = .)),
model2 = tidy(lm(score ~ age + gender, data = .))) %>%
gather(model_name, model, -setid) %>%
unnest() %>%
filter(term == "age")
interval1 <- -qnorm((1-0.9)/2)
ggplot(temp, aes(colour = as.factor(setid))) +
geom_hline(yintercept = 0, colour = gray(1/2), lty = 2) +
geom_linerange(aes(x = model_name, ymin = estimate - std.error*interval1,
ymax = estimate + std.error*interval1),
lwd = 1, position = position_dodge(width = 1/2)) +
scale_x_discrete(limits=c("model2", "model1"), labels=c("M2", "M1")) +
coord_flip()
(This question is once asked in Japanese Stackoverflow, but couldn't get answers.)
Upvotes: 2
Views: 2763
Reputation: 43334
You can change the width
parameter of position_dodge
to a negative. This does produce a warning:
Warning message: position_dodge requires non-overlapping x intervals
but plots fine:
ggplot(temp, aes(colour = as.factor(setid))) +
geom_hline(yintercept = 0, colour = gray(1/2), lty = 2) +
geom_linerange(aes(x = model_name, ymin = estimate - std.error*interval1,
ymax = estimate + std.error*interval1),
lwd = 1, position = position_dodge(width = -1/2)) +
scale_x_discrete(limits=c("model2", "model1"), labels=c("M2", "M1")) +
coord_flip()
Upvotes: 3