Rilcon42
Rilcon42

Reputation: 9763

ggplot adding scale_x apparently removes scale_y

I am trying to create a rotated barplot with names on the Y axis and values (-0.5, 0, 0.5) on the X axis. I have the barplot working, but when I try to add scale_x_discrete the Y axis labels vanish. What am I doing wrong?

dtm <- data.frame(
  month = factor(c("Police","Country","Rules")), 
  value = c(-.51,-.1,.9)
)
dtm$colour <- ifelse(dtm$value < 0, "firebrick1","steelblue")

ggplot(dtm, aes(month, value, label = month)) + geom_text(aes(label=value), position = position_dodge(width = .9)) + 
  geom_bar(stat = "identity",aes(fill = colour))+ 
  coord_flip() + labs(x = "", y = "") +
  scale_y_continuous(breaks = NULL,labels=dtm$month) +theme_bw()

This line causes issues

  scale_x_discrete("Day of the Week",breaks = NULL,labels=c(-1,-.5,0,.5,1)) + 

Upvotes: 0

Views: 71

Answers (1)

Mako212
Mako212

Reputation: 7292

When you use coord_flip the x axis becomes the y axis, and vice versa. I'd suggest putting it last so it's not confusing. Also setting labs blank was causing some issues when you overrode it with scale_x_discrete

  g1 <- ggplot(dtm, aes(month, value, label = month)) + geom_text(aes(label=value, hjust = ifelse(value >=0,-.1,1.2)), position = position_dodge(width = .9)) + 
    geom_bar(stat = "identity",aes(fill = colour))+ 
    scale_y_continuous(breaks =seq(-1,1,.5),  labels=seq(-1,1,.5),expand=c(.1,.1)) +
    scale_x_discrete("Day of the Week")+
    coord_flip() +
    theme_bw()

I used an ifelse statement in geom_text to set the hjust based on whether value is positive or negative. I also added expand=c(.1,.1) to scale_y_continuous to add a little padding so the labels aren't covered up.

enter image description here

Upvotes: 3

Related Questions