ggplot辅助轴错误的图例颜色

时间:2018-06-01 07:45:05

标签: r ggplot2

我一直在尝试使用辅助轴创建一个绘图,但正如您在下面看到的那样,R会将图例中的所有线条颜色更改为蓝色,而不仅仅是辅助轴的颜色:

library(ggplot2)
library(reshape2)

prev <- data.frame(
            YEAR = seq(1990,1995),
            GP   = c(7,9,14,12,11,12),
            HOSPITAL = c(0,0,0,0,0.5,0.8)
)

d <- melt(prev, id.vars="YEAR")
names(d)[2] <- "Datasets"

prev2 <- data.frame(
            YEAR = seq(1990,1995),
            Datasets = rep("REFERRALS",6),
            value = c(0.5,0.9,1.2,3,7,11)
)

ggplot(d, aes(YEAR, value, linetype=Datasets), show.guide=FALSE) +
  geom_line() +
  scale_linetype_manual(values=c("solid","dashed","solid")) +
  scale_x_discrete(limits=seq(1990,1995,1)) +
  geom_vline(xintercept=1991, col="darkgrey") +
  geom_vline(xintercept= 1994, col="darkgrey") +
  geom_line(data=prev2, aes(y=value), col="blue") +
  scale_y_continuous(sec.axis=sec_axis(~.*7,name="number of referrals")) +
  theme_bw() + xlab("\nYear") + ylab("Prevalence") +
  theme(legend.justification=c(.1,.9), legend.position=c(.05,.96),
        legend.title=element_blank(),
        plot.margin = unit(c(.5,.5,.5,.5), "cm"),
        axis.title.y.right = element_text(color="blue"))

secondary axis

有没有人知道如何将图例中的线条颜色变为“GP”和“HOSPITAL”的黑色?

2 个答案:

答案 0 :(得分:3)

您可以在指南中控制颜色:

+ guides(linetype = guide_legend(override.aes = list(color = "red")))

这里我使用红色突出显示这适用于任意颜色。你当然想要color = c("black", "black", "blue")

resulting plot

答案 1 :(得分:1)

只需将您的通话顺序更改为geom_line即可。像这样:

ggplot(d, aes(YEAR, value, linetype=Datasets), show.guide=FALSE) +
  geom_line(data=prev2, aes(y=value), col="blue") +
  geom_line() +
  scale_linetype_manual(values=c("solid","dashed","solid")) +
  scale_x_discrete(limits=seq(1990,1995,1)) +
  geom_vline(xintercept=1991, col="darkgrey") +
  geom_vline(xintercept= 1994, col="darkgrey") +

  scale_y_continuous(sec.axis=sec_axis(~.*7,name="number of referrals")) +
  theme_bw() + xlab("\nYear") + ylab("Prevalence") +
  theme(legend.justification=c(.1,.9), legend.position=c(.05,.96),
        legend.title=element_blank(),
        plot.margin = unit(c(.5,.5,.5,.5), "cm"),
        axis.title.y.right = element_text(color="blue"))