I need to replace very long axis labels in a ggplot with more informative names stored in the dataframe from which the plot is drawn.
For some reasons (see Replacing axis labels with scale_x_discrete) ggplot fails to do so.
Here is an example of the original plot x-axis:
The original labels (n=256) are grouped in a way, that three of them belong to the same factor level (basically, they are replicates).
The solution is to create a vector, which specifies the replacing label for each of the original labels.
z <- c("SKF1_sample_001" = "Cat1",
"SKF1_sample_002" = "Cat1",
"SKF1_sample_003" = "Cat1",
"SKF1_sample_004" = "Catn",
.....) ### for all 256 labels ### note that "Catn" does not follow a logical pattern
and use this vector in scale_x_discrete(labels = z)
I do not want to write a vector with 256 revalues, so i am trying to extract this from the dataframe (see the link above, how this fails when used directly).
I am collecting the required data (original and replacement labels) in tmp
.
From tmp
i want to extract a vector which can be used by ggplot2 for scale_x_discrete()
, so it must put the extracted values in “” and separates all value pairs with “,”, exactly as in vector z
.
Any help is appreciated!
Here is an example data set:
tmp <- data.frame(Original = c("Sample001", "Sample002", "Sample003", "Sample004", "Sample005"),
Replacement = c("Cat1", "Cat1", "Cat1", "Cat2", "Cat2"))
I tried z <- paste(tmp$Original,"=", tmp$Replacement, collapse = ",")
, which is not working with ggplot2! The obtained vector does not feature the “”.