2017-02-17 95 views
1

我有一个像下面这样的图,我想改变颜色线从蓝 - >绿 - >红到红 - > g-> b的顺序,以便它是与传说的顺序相同。我发现了几个教程来改变传说的顺序,但我想在这种情况下保持顺序(因为它们是1,2和3)。ggplot2:改变颜色的顺序

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() 

(这个问题被问过在日本#1,但未能得到答案。)

+0

哪个包是'从tidy'功能?我确信我已经看到了,但'tidyverse'没有给出结果 – GGamba

+0

@GGamba,它应该是'扫帚'。 – thepule

+4

只需将'position'改为'position_dodge(width = -1/2)' – alistaire

回答

1

可以的position_dodgewidth参数更改为负。这确实会产生一个警告:

Warning message: 
position_dodge requires non-overlapping x intervals 

但情节罚款:

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()