Home > Software engineering >  Setting limits to a discrete data based x-axis
Setting limits to a discrete data based x-axis

Time:03-24

I am struggling to make a graph, using ggplot2. below, you can see the output I get and the relative code:

enter image description here

library(ggplot2)

## Defining Dataframe
Dati <- data.frame(Correction = c("0%", " 5%", " 10%", " 15%"), 
                 Vix = c(65700, 48000, 45500, 37800))

## Create factors
Dati$Correction <- as.factor(Dati$Correction)
Dati$Correction <- factor(Dati$Correction, levels = c("0%", " 5%", " 10%", " 15%"))



## Defining graph
Graph <- ggplot(data=Dati, aes(x=Correction, y=Vix))   geom_point(color = "#e60000", shape = 1, size = 3.5)   
geom_smooth(aes(as.numeric(Correction), Vix), level=0.75, span = 1, color = "#e60000", method=lm)   
xlab("xlab")   ylab("y lab")   labs(color='')  
guides(color = FALSE, size = FALSE)
Graph

What I would like is to set the limits, perhaps with scale_x_discrete() but I am not succeeding with it, so as to remove the external space before and after the line:

enter image description here

Is it possible to do somehow? I would like to do this also in case in x-axis would be presents textual values.

thank you in advance for every eventual help.

CodePudding user response:

You should set an expand in the scale_x_discrete function. This will change the limits of your discrete x-axis. You can change this to what you want. You can use this code:

 ## Defining graph
 Graph <- ggplot(data=Dati, aes(x=Correction, y=Vix))   geom_point(color = "#e60000", shape = 1, size = 3.5)   
   geom_smooth(aes(as.numeric(Correction), Vix), level=0.75, span = 1, color = "#e60000", method=lm)   
   xlab("xlab")   ylab("y lab")   labs(color='')  
   guides(color = FALSE, size = FALSE)   
   scale_x_discrete(expand=c(0.05, 0))
 Graph

Output:

enter image description here

CodePudding user response:

The x axis is a continuous variable, so you need to use scale_x_continuous(). To remove the padding on the scale, set scale_x_continuous(expand = c(0, 0))

  • Related