Show legend marker and label even if not in plot

Hi all,

Suppose I have this dataframe:

# packages

# data
genes <- c("gene1", "gene2", "gene2")
tissue <- c("Blood", "Nerve", "Brain")
pval <- c(0.8, 0.6, 0.005)

df <- data.frame(col_x = tissue,
                 col_y = genes,
                 p = pval)

I create a column for labeling purposes in the plot:

df <- df %>%
  mutate(`Post. Prob.` = ifelse(`p`>= 0.5, "P > 0.5",
                         ifelse(`p`>= 0.01 & `p`<= 0.5, "P > 0.01","Not sig")))

The remaining code is for different aesthetics in the plot.

# black ring if P>0.5
# gray ring if between 0.01 and 0.5
# white ring if not sig
ring_df <- df %>%
  select(`Post. Prob.`) %>%
  mutate(`ring` = ifelse(`Post. Prob.` == "P > 0.5", "black",
                         ifelse(`Post. Prob.` == "P > 0.01", "gray", "white")))
rings <- ring_df$ring
names(rings) <- ring_df

Now I create the plot:

  geom_point(aes(x=`col_x`, y=`col_y`,
                 color=`Post. Prob.`),
             shape=21, # so I can fill and color
             stroke = ifelse(df$`Post. Prob.` == "P > 0.5",2,
                             ifelse(df$`Post. Prob.` == "P > 0.01", 2, 0.5)))+ # stroke facilitates thickness of point edge
                     breaks=c("P > 0.5", "P > 0.01", "Not Sig."),
                     labels=c("P > 0.5", "P > 0.01", "Not Sig."),
                     name="Post. Prob.")+

However, my question is that in the legend, the plot only shows P > 0.5. I know that none of the points follow the other parameters, but how do I make it so that the gray legend marker would show? For example, I would like the P > 0.1 legend marker and Not sig legend marker to be shown in the legend.

Let's assume the pval for Nerve is .09, so that we can also cover the p-values between .01 and .5. If you set up proper names for your object rings as Post. Prob. and adjust the colour with scale_color_manual(values=rings), you will produce the desired chart.

As you define the color in aes, all you need to specify is the colours you want in scale_color_manual, without passing the breaks and labels.


This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.