In ggplot2; How can I move the x axis on top in this case then rotate the axes with coord_flip ()?

Viewed 468

I have tried to move the x axis to the top with: scale_x_discrete (position = "top") but it indicates error. Anyone help me please?

require(ggplot2)
a <- c("ENE","FEB","MAR","ABR","MAY","JUN","JUL","AGO","SET","OCT","NOV","DIC")
b <- c(0,0,0,0,18,133,316,55,242,36,13,0)
df <- data.frame("mes"=a,"tot"=b)

p <- ggplot(df, aes(x=mes, y=tot))+
  geom_col(colour="black", fill="gray")+
  labs(x="meses", y="ocurrencias")+
  theme_bw()+ 
  theme(
        panel.grid.minor=element_blank(),
        plot.title = element_text(size=16,face="bold",hjust=0.5),
        plot.subtitle = element_text(size=15,hjust=0.5),
        axis.title.y=element_blank(),
        axis.text.y=element_blank(),
        axis.text=element_text(size=12,face="bold"),
        axis.title=element_text(size=14,face="bold")
    )+
   geom_text(aes(label=mes),
             vjust=0.5, hjust=-0.2,
             color='black', size=5, fontface = "bold")
p <- p + coord_flip()
plot(p)

1 Answers

This could be achieved like so.

  1. Swap x and y instead of using coord_flip
  2. Use scale_x_continuous(position = "top")

Or stick with coord_flip and use scale_y_continuous(position = "right") (after flipping y becomes x and right becomes top). (;

library(ggplot2)
a<-c("ENE","FEB","MAR","ABR","MAY","JUN","JUL","AGO","SET","OCT","NOV","DIC")
b<-c(0,0,0,0,18,133,316,55,242,36,13,0)
df<-data.frame("mes"=a,"tot"=b)

p<-ggplot(df,aes(y=mes, x=tot))+
  geom_col(
    colour="black",fill="gray")+
  labs(x="meses", y="ocurrencias")+theme_bw()+ 
  theme(
    panel.grid.minor=element_blank(),
    plot.title = element_text(size=16,face="bold",hjust=0.5),
    plot.subtitle = element_text(size=15,hjust=0.5),
    axis.title.y=element_blank(),
    axis.text.y=element_blank(),
    axis.text=element_text(size=12,face="bold"),
    axis.title=element_text(size=14,face="bold")
  )+
  geom_text(
    aes(label=mes),vjust=0.5,hjust=-0.2,
    color='black', size=5,fontface = "bold") +
  scale_x_continuous(position = "top")
p

Related