Change axis labels when plotting a numerical vector against an "as.numeric" factor

Viewed 675

I was searching unsuccessfully to figure out a way to keep axes labeled a specific way after creating a linear model plot.

My data is

    Sample                  ActB
    Pre-Amp_Ctrl cDNA       5.607907144
    Pre-Amp_Ctrl cDNA 10e-1 8.916634343
    Pre-Amp_Ctrl cDNA 10e-2 12.6501345
    Pre-Amp_Ctrl cDNA 10e-3 16.32385192
    Pre-Amp_Ctrl cDNA 10e-4 20.30327678
    Pre-Amp_Ctrl cDNA 10e-5 23.40471201

When I plot this normally

    ggplot(NP, aes(x=NP$Sample, y=NP$actbct)) +
    geom_point()

I get this:

enter image description here

where the samples are labeled on the ticks.

However when I try to add a trend line, I have to change the factor vector to "as.numeric" and I lose the labeled ticks.

    ggplot(NP, aes(x=as.numeric(NP$Sample), y=NP$actbct)) +
    geom_point() +
    geom_smooth(method= "lm", color = "red")

and get this image instead:

enter image description here

Any possible way to keep the samples labeled while also having the trendline? I know I can do it in Excel, but it'd be great to also be able to do it in R.

2 Answers

Use scale_x_continuous to specify labels. As they are long their I changed angle and position of them too.

NP <- read.csv("tmp", header = T)

library(ggplot2)
ggplot(NP, aes(as.numeric(Sample), ActB)) +
    geom_point() +
    geom_smooth(method = "lm", color = "red") +
    scale_x_continuous(breaks = 1:nrow(NP), labels = NP$Sample) +
    labs(x = "Sample") +
    theme(axis.text.x = element_text(angle = 70, hjust = 1))

enter image description here

NP <- read.table(text='
Sample ActB
"Pre-Amp_Ctrl cDNA" 5.607907144
"Pre-Amp_Ctrl cDNA 10e-1" 8.916634343
"Pre-Amp_Ctrl cDNA 10e-2" 12.6501345
"Pre-Amp_Ctrl cDNA 10e-3" 16.32385192
"Pre-Amp_Ctrl cDNA 10e-4" 20.30327678
"Pre-Amp_Ctrl cDNA 10e-5" 23.40471201
', header=T)

library(ggplot2)
   ggplot(NP, aes(x=NP$Sample, y=NP$ActB)) +
    geom_point() +
    geom_smooth(aes(x=as.numeric(NP$Sample), y=NP$ActB), method= "lm", color = "red")

enter image description here

Related