I created a bar chart with quartals on the x-axis.
My problem is that, the values for the quartals are: 20191, 20192, 20193, 20194, 20201, 20202, 20203 etc.
So if I create the plot there is space between 20194 and 20201.
I guess thats related to the fact that the x-axis is numerical.
Is there a way to delete the space between 20194 and 20201?
I created an example dataset:
Quartal <- c(rep(20191, 3), rep(20192, 3), rep(20193, 3), rep(20194, 3), rep(20201, 3),rep(20202, 3))
Condition <- rep(c("Value1", "Value2", "Value3"), 6)
Values <- c(100, 150, 125, 200, 185, 300, 400, 100, 150, 200, 225, 300, 100, 150, 125, 400, 350, 300)
The Code I used to create the chart:
dataset <- data.frame(Quartal, Condition, Values)
ggplot(dataset, aes(Quartal, Values, group= Condition, colour=Condition, fill=Condition))+
geom_bar(stat="identity", position = position_dodge())

What I tried was to add a row of numerical calues to my dataset and than to plot the numerical values on the x-axis.
dataset$row_num<-seq(1:nrow(dataset))
ggplot(dataset, aes(row_num, Values, group= Condition, colour=Condition, fill=Condition))+
geom_bar(stat="identity", position = position_dodge())

The problem is, that I loose the space between the quartals. I guess the easiest way would be to delete the space in the first example. But I am open to other suggestions.
You can use function as.yearqtr from package zoo to coerce to a date quarters class. zoo supports ggplot2 and your plotting code takes care of the x axis automatically.
library(ggplot2)
library(zoo)
Quartal <- c(rep(20191, 3), rep(20192, 3), rep(20193, 3), rep(20194, 3), rep(20201, 3),rep(20202, 3))
Condition <- rep(c("Value1", "Value2", "Value3"), 6)
Values <- c(100, 150, 125, 200, 185, 300, 400, 100, 150, 200, 225, 300, 100, 150, 125, 400, 350, 300)
Qrtl <- as.yearqtr(as.character(Quartal), format = "%Y%q") |> format("%Y Q%q")
dataset <- data.frame(Quartal, Qrtl, Condition, Values)
ggplot(dataset, aes(Qrtl, Values, group= Condition, colour=Condition, fill=Condition))+
geom_bar(stat="identity", position = position_dodge())
It is probably better to transform the data set in a dplyr pipe, as follows.
library(ggplot2)
library(zoo)
library(dplyr)
Quartal <- c(rep(20191, 3), rep(20192, 3), rep(20193, 3), rep(20194, 3), rep(20201, 3),rep(20202, 3))
Condition <- rep(c("Value1", "Value2", "Value3"), 6)
Values <- c(100, 150, 125, 200, 185, 300, 400, 100, 150, 200, 225, 300, 100, 150, 125, 400, 350, 300)
dataset <- data.frame(Quartal, Condition, Values)
dataset %>%
mutate(Quartal = as.yearqtr(as.character(Quartal), format = "%Y%q"),
Quartal = format(Quartal, "%Y Q%q")) %>%
ggplot(aes(Quartal, Values, group= Condition, colour=Condition, fill=Condition))+
geom_bar(stat="identity", position = position_dodge())

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With