Home > Blockchain >  How to order continuous x-axis on regression graph in ggplot2 R?
How to order continuous x-axis on regression graph in ggplot2 R?

Time:05-05

I want x-axis to go from 400 to 100. Here is my attempt, which did not work.

set.seed(111)
var <- rep(c("SP1","SP2","AB1","AB2"), times = 5)
var.val <- rnorm(20,5,1)
level <- rep(c(100,200,300,400), each = 5)

df <- data.frame(var, var.val, level)

df <- df[order(-level),]

ggplot(df, aes(x = level, y = var.val, col = var, group = var, linetype = var))   # set linetype
  geom_point(aes(fill = var), colour="white",pch=21, size=4, stroke = 1,
             alpha = 0.7, data = df[df$var %in% c("SP1", "SP2"),])  
  theme_classic()   
  geom_smooth(data = df[df$var %in% c("SP1", "SP2"),],
              method = "lm", formula = y ~ x, alpha = 0.2)  
  geom_smooth(data = df[!df$var %in% c("SP1", "SP2"),],
              method = "lm", formula = y ~ x, se = FALSE)    
  scale_linetype_manual(values = c("dotdash", "dashed","solid", "solid"))   
  scale_colour_manual(values = c("black","black","red","blue"))

enter image description here

CodePudding user response:

Try adding scale_x_reverse()

library(tidyverse)


set.seed(111)
var <- rep(c("SP1","SP2","AB1","AB2"), times = 5)
var.val <- rnorm(20,5,1)
level <- rep(c(100,200,300,400), each = 5)

df <- data.frame(var, var.val, level)

df <- df[order(-level),]

ggplot(df, aes(x = level, y = var.val, col = var, group = var, linetype = var))   # set linetype
  geom_point(aes(fill = var), colour="white",pch=21, size=4, stroke = 1,
             alpha = 0.7, data = df[df$var %in% c("SP1", "SP2"),])  
  theme_classic()   
  geom_smooth(data = df[df$var %in% c("SP1", "SP2"),],
              method = "lm", formula = y ~ x, alpha = 0.2)  
  geom_smooth(data = df[!df$var %in% c("SP1", "SP2"),],
              method = "lm", formula = y ~ x, se = FALSE)    
  scale_linetype_manual(values = c("dotdash", "dashed","solid", "solid"))   
  scale_colour_manual(values = c("black","black","red","blue"))  
  scale_x_reverse()

Created on 2022-05-04 by the reprex package (v2.0.1)

  • Related