Scale_colour_manual错误"手动刻度值不足"

时间:2018-03-31 13:34:35

标签: r ggplot2

我有一个像这个例子的数据集:

percentile  average group
1   11.65   ID1
2   12.84   ID1
3   13.61   ID1
4   14.02   ID1
5   14.25   ID1
6   14.45   ID1
1   11.66   ID2
2   12.84   ID2
3   13.58   ID2
4   14.01   ID2
5   14.28   ID2
6   14.46   ID2

在完整数据集中,每8 IDs我有100 rowsIDs。我正在尝试使用此命令创建density plot in R

library(ggplot2)
data <- read.table("data.csv", sep=",", header = T )
data$percentile <- factor(data$percentile, levels = data$percentile)
pdf("Ala_all.pdf",width=20,height=10)
d = ggplot(data=data, aes(x=percentile, y=average, group=group, shape=group, colour=group)) +
     geom_line(size=2) + coord_cartesian(ylim = c(0, 17))
d + scale_color_manual(values=c("#bbbbbb", "#ff6362", "#b1b1ff", "#282828", "#b30100", "#0100b1", "#2927ff", "#000000") )
dev.off()

但是,它会提供此error

> d + scale_color_manual(values=c("#bbbbbb", "#ff6362") )Error: Insufficient values in manual scale. 12 needed but only 2 provided.
In addition: Warning message:
In `levels<-`(`*tmp*`, value = if (nl == nL) as.character(labels) else paste0(labels,  :
  duplicated levels in factors are deprecated

1 个答案:

答案 0 :(得分:0)

错误在于data$percentile <- factor(data$percentile, levels = data$percentile)。您正在设置多个级别的因子。您可能需要unique()

library(ggplot2)

mydata <- read.table(header = TRUE, text = "
percentile  average group
1   11.65   ID1
2   12.84   ID1
3   13.61   ID1
4   14.02   ID1
5   14.25   ID1
6   14.45   ID1
1   13.66   ID2
2   14.84   ID2
3   15.58   ID2
4   16.01   ID2
5   16.28   ID2
6   16.46   ID2")



mydata$percentile <- factor(mydata$percentile, levels = unique(mydata$percentile))

d <-
  ggplot(mydata,
         aes(
           x = percentile,
           y = average,
           group = group,
           shape = group,
           colour = group
         )) +
  geom_line(size = 2) +
  coord_cartesian(ylim = c(0, 17))


d + scale_color_manual(values = c("#bbbbbb", "#ff6362") )

enter image description here