Larsq
Larsq

Reputation: 365

geom_col() with values close to each other in ggplot


I encountered a problem in the function geom_col(). It seems to work fine if my x-values are sufficiently wide apart, but if they are 'close', my plot does not show as expected. See example below.

In a similar existing issue, it was suggested to set width manually, but that does not resolve the problem.

Furthermore, one should expect the first and second plot to work in the same way. However in the second plot, the default settings seems to change the axis

Is this a bug? Or do I miss an option?

# library(ggplot2)

# plot that does work
df <- data.frame(x = c(1,2,3,5,6), y = c(45,45,45,45,45))
ggplot(df, aes(x = x, y = y)) + geom_col()

# plot that does not work (only different numbers)
df <- data.frame(x = c(0.9,0.91,0.92,1.0,1.01), y = c(45,45,45,45,45))
ggplot(df, aes(x = x, y = y)) + geom_col()

# plot that still does not work, with manual setting of width (you can try different options)
ggplot(df, aes(x = x, y = y)) + geom_col(width = 0.05)

# plot showing that there are at least 5 seperate bars, only I expect y to be the height of the bar and x to be the groups
ggplot(df, aes(x = x, y = y)) + geom_col(position = 'dodge2', colour = "black")

Upvotes: 1

Views: 367

Answers (1)

caldwellst
caldwellst

Reputation: 5956

So the option you are missing is orientation, which helps specify the axis to run along. geom_col guesses the correct orientation, and in your second df, it is guessing to run along the y-axis, hence we need to specify to instead run along the x-axis.

df <- data.frame(x = c(0.9,0.91,0.92,1.0,1.01), y = c(45,45,45,45,45))
ggplot(df, aes(x = x, y = y)) + geom_col(orientation = 'x')

enter image description here

Upvotes: 1

Related Questions