从图例中删除特定标签

时间:2016-12-20 21:22:19

标签: r ggplot2

根据下面的数据和图表,如何从图例中删除显示为“NA”的类别?我只想让图例显示类别ABC的颜色。

library(tibble)
library(ggplot2)

mydata <- tibble(Time_dim = rep(1:10, 10),
                 Category = c(rep(NA, 10), rep(c(rep("A", 10), rep("B", 10), rep("C", 10)), 3)),
                 Attribute = c(rep("alpha", 10), rep("beta", 30), rep("omega", 30), rep("theta", 30)),
                 Data = runif(100))
mydata$Category <- factor(mydata$Category)
mydata$Attribute <- factor(mydata$Attribute)

ggplot(mydata, aes(x = Time_dim, y = Data, colour = Category)) +
geom_line() + facet_wrap(~ Attribute, ncol = 1, scales = "free")

enter image description here

2 个答案:

答案 0 :(得分:3)

您可以将breaks比例中的color设置为仅显示的类别。

在您的情况下,您可以使用颜色因子的levels

scale_color_discrete(breaks = levels(mydata$Category))

答案 1 :(得分:0)

将此添加到ggplot

+ scale_colour_manual(breaks=c("A", "B", "C"), values=c("red", "green", "blue"))