Niek de Klein
Niek de Klein

Reputation: 8834

Change color of one variable in ggplot

I have a dataframe

> head(sample_data_df)

             Gene_1     Gene_2      Gene_3     Gene_4     Gene_5
Sample_1 -1.1698306  1.2408295  1.42964624 -0.2323205  0.1669285
Sample_2 -0.6983788 -0.9224843  2.21307158 -0.3003344 -0.5299774
[...]

that I melt with

sample_data_melt <- melt(sample_data_df)

  variable      value
1   Gene_1 -1.1698306
2   Gene_1 -0.6983788

and plot with

ggplot(sample_data_melt, aes(x=variable,y=value)) + 
  geom_point(position = "jitter")

I would like to change the alpha of all samples (rows in sample_data_df) to be 0.5 except for one sample. I know I can set it different per point by making an alpha vector like

alpha <- rep(0.1,5005)
alpha[seq(0, 5005, by= 1001)] <- 1
ggplot(sample_data_melt, aes(x=variable,y=value)) + 
  geom_point(position = "jitter",alpha = alpha)

but how do I set one specific sample as alpha 1?

Upvotes: 0

Views: 460

Answers (1)

Gregor Thomas
Gregor Thomas

Reputation: 146144

It seems like there is valuable information in the row names that gets lost when you melt (the sample numbers). I'd recommend keeping this around:

sample_data_df$sample = row.names(sample_data_df)
sample_data_melt = melt(sample_data_df, id.vars = "sample")

You can then set an indicator for the sample you want to be fully opaque

sample_data_melt$alpha = ifelse(sample_data_melt$sample == "Sample_2", "Sample 2", "Other")

And map that to alpha in your plot:

ggplot(sample_data_melt, aes(x=variable,y=value)) + 
    geom_point(aes(alpha = alpha), position = "jitter") +
    scale_alpha_manual(values = c(0.5, 1))

(Untested as your data isn't shared reproducibly, please use dput() or simulate data if you want tested answers.)

Upvotes: 2

Related Questions