Shira
Shira

Reputation: 129

ggplot2 bar charts - how to specify x-axis positions of bars?

Below is my code, but I want a gap between the "overall" bar and the other two bars. How do I specify the x-axis positions of the bars?

library(tidyverse)

df <- data.frame(group = factor(c("overall", "low-income", "high-income"), 
                              levels = c("overall", "low-income", "high-income")), 
                 AUC = c(0.70, 0.60, 0.80))
ggplot(df) +
  geom_col(aes(x=group, y=AUC)) +
  theme(axis.title.x=element_blank())

current bar chart

Upvotes: 2

Views: 743

Answers (2)

Darren Tsai
Darren Tsai

Reputation: 35554

Another option similar to @G.Belton, but you don't need to change your data. Use scale_x_discrete to exchange or add bar levels.

ggplot(df) +
  geom_col(aes(x = group, y = AUC)) +
  scale_x_discrete(limits = c("overall", "", "low-income", "high-income")) +
  theme(axis.title.x = element_blank())

enter image description here

Upvotes: 3

G. Belton
G. Belton

Reputation: 133

Add a column between "overall" and "low-income." Give that column a value of 0 and a blank label.

library(tidyverse)

df <- data.frame(group = factor(c("overall", " ", "low-income", "high-income"), 
                                levels = c("overall", " ","low-income", "high-income")), 
                 AUC = c(0.70, 0, 0.60, 0.80))
ggplot(df) +
  geom_col(aes(x=group, y=AUC)) +
  theme(axis.title.x=element_blank())

Upvotes: 3

Related Questions