Search code examples
rggplot2bar-chart

Ggplot barchart


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())

That's how the chart looks like

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())

However, then the barchart looks like this:

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.


Solution

  • The problem arises because the values on the x-axis (Quartal) are treated as numbers rather than categories. As a result, the values 20194 and 20201 are spaced apart because they are not consecutive numerically. The solution is to convert the Quartal variable into a factor so that the x-axis is treated as discrete.

    dataset$Quartal <- factor(dataset$Quartal, levels = unique(dataset$Quartal))
    
    ggplot(dataset, aes(x = Quartal, y = Values, group = Condition, fill = Condition)) +
      geom_bar(stat = "identity", position = position_dodge()) +
      theme_minimal()
    

    Output:

    enter image description here