Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
472 views
in Technique[技术] by (71.8m points)

r - Putting x-axis at top of ggplot2 chart

I feel like this should be obvious... all I'm trying to do is to remove the x-axis from the bottom of my graph and add it to the top.

Here is a reproducible example. Data plus code to make the following graph:

library(reshape2)
library(ggplot2)

data(mtcars)
dat <- with(mtcars, data.frame(mpg, cyl, disp, hp, wt, gear))
cor.matrix <- round(cor(dat, use = "pairwise.complete.obs", method = "spearman"), digits = 2)
diag(cor.matrix)<-NA

cor.dat <- melt(cor.matrix)
cor.dat <- data.frame(cor.dat)
cor.dat <- cor.dat[complete.cases(cor.dat),]


ggplot(cor.dat, aes(Var2, Var1, fill = value)) + 
  geom_tile(colour="gray90", size=1.5, stat="identity") + 
  geom_text(data=cor.dat, aes(Var2, Var1, label = value), color="black", size=rel(4.5)) +
  scale_fill_gradient(low = "white", high = "dodgerblue", space = "Lab", na.value = "gray90", guide = "colourbar") +
  scale_x_discrete(expand = c(0, 0)) +
  scale_y_discrete(expand = c(0, 0)) +
  xlab("") + 
  ylab("") +
  theme(panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        panel.border = element_rect(fill=NA,color="gray90", size=0.5, linetype="solid"),
        axis.line = element_blank(),
        axis.ticks = element_blank(),
        panel.background = element_rect(fill="gray90"),
        plot.background = element_rect(fill="gray90"),
        legend.position = "none", 
        axis.text = element_text(color="black", size=14) )

enter image description here

But what I'm trying to produce is- it seems like this should be obvious (e.g. it's very easy to do in base-R) , but I haven't managed to find what I'm looking for in ggplot2.

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can move the x-axis labels to the top by adding

scale_x_discrete(position = "top") 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...