R ggplot2将图例文本固定为值和颜色

时间:2019-03-03 02:55:23

标签: r ggplot2 colors

我有一个数字列表l(在我的情况下是3600,代表我之前计算过的不同类别(0、2、3、4、5、6、7、8)。现在我要绘制一个网格,其中列表中的每个数字代表一种特定的颜色(即0->始终为黑色,3->始终为橙色...)。

但是我想用数字代替图例中的类别。当所有类别都在列表中时,我的代码可以正常工作。在某些情况下,并不是每个类别都出现在我的列表中(取决于数据)。

如何将标签与类别(数字)链接,以便在任何情况下都能显示正确的颜色,或者正确地描述颜色?

# example list
l <- list(sample(c(0,2:8), 3600, replace = TRUE))

# building a data.frame for the grid
C <- as.data.frame(unlist(l))
colnames(C) <- c("category")

y.df <- rep(1:60, each = 60)
x.df <- rep(1:60, times = 60)
z.df <- rep(1:3600, times = 1)

C <- cbind(C, x = x.df, y = y.df, node_chem = z.df)

myColors <- c("black", "darkorchid1", "orange", "red",
              "springgreen", "darkgreen", "cyan", "white")
names(myColors) <- c ("0", "2", "3", "4", "5", "6", "7", "8")

ggplot(data=C, aes(x = x, y = y,  color = factor(C$category))) +    
  geom_point() +

  # background = white
  theme_bw() +

  scale_color_manual(name= "category",
                     values= myColors,
                     labels = c("category 0", "category 2", "category 3", "category 4", 
                                "icategory 5", "category 6", "category 7", "category 8")) +

  #scale_colour_gradientn(colours=rainbow(4)) +
  ggtitle("my map")

在计算所有类别之前,这里是输出:

enter image description here

1 个答案:

答案 0 :(得分:0)

创建一个包含类别标签的列,然后可以将其提供给颜色美观。

# example list
l <- list(sample(c(0,2:8), 3600, replace = TRUE))

# building a data.frame for the grid
C <- as.data.frame(unlist(l))
colnames(C) <- c("category")

y.df <- rep(1:60, each = 60)
x.df <- rep(1:60, times = 60)
z.df <- rep(1:3600, times = 1)

C <- cbind(C, x = x.df, y = y.df, node_chem = z.df)

myColors <- c("black", "darkorchid1", "orange", "red",
              "springgreen", "darkgreen", "cyan", "white")

# change the named vector to match the category labels
names(myColors) <- paste("category", c("0", "2", "3", "4", "5", "6", "7", "8"), sep = " ")

# make a new column containing the desired category labels
C$category2 <-  paste("category", C$category, sep = " ")

ggplot(data = C, aes(x = x, y = y,  color = factor(category2))) +    
  geom_point() +

  # background = white
  theme_bw() +

  scale_color_manual(name= "category",
                     values= myColors) +

  ggtitle("my map")

现在,如果您删除其中一个类别,它将仍然有效,因为您在scale_color_manual中命名的向量将正确地映射颜色:

ggplot(data = C[C$category != 0,], aes(x = x, y = y,  color = factor(category2))) +    
geom_point() +

  # background = white
  theme_bw() +

  scale_color_manual(name= "category",
                     values= myColors) +

  ggtitle("my map")

enter image description here