2
df<-data.frame(adjuster=c("Mary","Mary","Bob","Bob","Mary"), 
           date=as.Date(c("2012-1-1","2012-2-1","2012-3-1","2012-4-1","2012-5-1")), 
           total=c(10,15,25,15,20), paid=c(5,5,10,10,15))
ggplot(df)+geom_point(aes(x=date,y=total,color=adjuster,group=1))+
  geom_line(aes(x=date,y=paid,group=2,color="Paid"))+scale_color_discrete(name="Legend")+
  geom_line(aes(x=date,y=total,color=adjuster,group=1))

在此处输入图像描述

我想强制“付费”行始终为黑色,但让其他行采用 ggplot 提供的默认颜色。我该如何做到这一点?

4

2 回答 2

2

这种方式付费列被添加为一个单独的层,但这意味着它不在图例中。我不明白为什么 Paid 列会出现在具有不同级别调整器的图例中。这是为什么?

library(ggplot2)
df <- data.frame(adjuster=c("Mary","Mary","Bob","Bob","Mary"), 
           date=as.Date(c("2012-1-1","2012-2-1","2012-3-1","2012-4-1","2012-5-1")), 
           total=c(10,15,25,15,20), paid=c(5,5,10,10,15))

ggplot(df, aes(x=date,y=total,color=adjuster,group=1)) + 
  geom_point() +
  geom_line(aes(x=date, y=total, color=adjuster, group=1)) +
  geom_line(aes(x=date, y=paid, group=2), data=df, colour="black") +
  scale_color_discrete(name="Legend")

在此处输入图像描述

于 2013-11-01T23:51:10.117 回答
1

这是一个可能的解决方案,可以使绘图代码更清晰,更符合 ggplot2 的设计精神。代价是您的数据需要重新排列一下。我还使用了一些额外的代码来动态生成颜色值的命名字符向量。感谢@John Colby 的gg_color_hue().

数据现在是“长格式”,所有 x 值和 y 值在两列中。此外,还有两个分组因素,将绘制线条的语义与着色线条和点的语义分开:

col_group line_group       date total
     Mary   Adjuster 2012-01-01    10
     Mary   Adjuster 2012-02-01    15
      Bob   Adjuster 2012-03-01    25
      Bob   Adjuster 2012-04-01    15
     Mary   Adjuster 2012-05-01    20
     Paid       Paid 2012-01-01     5
     Paid       Paid 2012-02-01     5
     Paid       Paid 2012-03-01    10
     Paid       Paid 2012-04-01    10
     Paid       Paid 2012-05-01    15

dat <- data.frame(col_group=c("Mary","Mary","Bob", "Bob", "Mary",
                              "Paid","Paid","Paid","Paid","Paid"),
                  line_group=c("Adjuster","Adjuster","Adjuster","Adjuster","Adjuster",
                               "Paid","Paid","Paid","Paid","Paid"), 
                  date=as.Date(c("2012-1-1","2012-2-1","2012-3-1","2012-4-1","2012-5-1",
                                 "2012-1-1","2012-2-1","2012-3-1","2012-4-1","2012-5-1")), 
                  total=c(10,15,25,15,20,
                          5, 5, 10,10,15))

# Color generating function found here:
# http://stackoverflow.com/questions/8197559/emulate-ggplot2-default-color-palette
gg_color_hue <- function(n) {
  hues = seq(15, 375, length=n+1)
  hcl(h=hues, l=65, c=100)[1:n]
}

# Dynamically generate default color values, but have Paid="black".
adj_names = sort(setdiff(unique(dat$col_group), "Paid"))
values = gg_color_hue(length(adj_names))
names(values) = adj_names
values = c(values, c(Paid="black"))

library(ggplot2)
plot1 <- ggplot(dat, aes(x=date, y=total, colour=col_group)) +
         geom_line(aes(group=line_group), size=1.2) +
         geom_point(size=2.8) +
         scale_colour_manual(values=values)

ggsave("plot1.png", plot=plot1, width=6, height=4.5, dpi=120)

在此处输入图像描述

于 2013-11-02T00:40:08.970 回答