Ivo
Ivo

Reputation: 4200

Get equal width bars and dense x-axis in ggplot barplot

I have the following data & code to produce a barplot (building on this answer)

tmpdf <- tibble(class = c("class 1", rep("class 2", 4), rep("class 3", 4)),
                var_1 = c("none", rep(c("A", "B", "C", "D"), 2)),
                y_ = as.integer(c(runif(9, min = 100, max=250))))

tmpdf <- rbind(tmpdf, cbind(expand.grid(class = levels(as.factor(tmpdf$class)),
                                        var_1 = levels(as.factor(tmpdf$var_1))),
                            y_ = NA))



ggplot(data=tmpdf, aes(x = class, y = y_, fill=var_1, width=0.75 )) +
  geom_bar(stat = "identity", position=position_dodge(width = 0.90), color="black", size=0.2)

This produces the below plot:

barplot

However, since not all class / var_1 combinations are present, some space on the x-axis is lost. I would now like to remove the empty space on the x-axis without making the bars wider(!).

Can someone point me to the right direction?

Upvotes: 0

Views: 159

Answers (2)

user18309711
user18309711

Reputation:

Technically, you could tweak a column chart (geom_col) to the desired effect, like so:

mpdf %>%
  mutate(xpos = c(1.6, 2 + .2 * 0:3, 3 + .2 * 0:3)) %>%
  ggplot() +
  geom_col(aes(x = xpos, y = y_, fill = var_1)) +
  scale_x_continuous(breaks = c(1.6, 2.3 + 0:1), labels = unique(mpdf$class))

However, the resulting barplot (condensed or not) might be difficult to interpret as long as you want to convey differences between classes. For example, the plot has to be studied carefully to detect that variable D runs against the pattern of increasing values from class 2 to 3.

Upvotes: 1

Ma&#235;l
Ma&#235;l

Reputation: 52209

You can use na.omit to remove unused levels, and then use facet_grid with scales = "free_x" and space = "free_x" to remove space.

ggplot(data=na.omit(tmpdf), aes(x = var_1, y = y_, fill=var_1, width=0.75)) +
  geom_col(position=position_dodge(width = 0.90), color="black", size=0.2) +
  facet_grid(~ class, scales = "free_x", space = "free_x", switch = "x") +
  theme(axis.text.x = element_blank(),
        axis.ticks.x = element_blank(),
        strip.background = element_blank())

enter image description here

Upvotes: 2

Related Questions