0

I am trying to move my y-axis tick marks closer to my heatmap.

Here is the code for the heatmap:

ggplot(p_typ_meta, aes(SampleType_Basic, Phylum, fill= Counts)) +geom_tile()+
scale_fill_gradient2(low="blue", mid="white",high="red",midpoint=.15)+theme(axis.title.x = element_text(size=13),axis.title.y = element_text(size=13),axis.text = element_text(size=11),axis.text.y=element_text(margin = margin(0,0)),legend.title.align=0.5, legend.title = element_text(size=13),legend.text = element_text(size=11),plot.title = element_text(hjust=0.5, size=15)) +labs(x="Sample Type", y="Microbial Phyla", title="Microbial Phyla & Sample Type",fill="Relative Abundance")+theme_classic()

I have tried the following:

theme(axis.text.y=element_text(hjust=0.5))
theme(axis.text.y=element_text(margin = margin(0,0)))
theme(axis.ticks.margin=unit(0,'cm'))
theme(axis.text.y = element_text(margin = margin(r = 0)))
scale_y_discrete(expand = c(0, 0))
scale_y_continuous(expand=c(0, 0))

Is there something I am missing in my code? Or is this just how heatmaps work in ggplot2?

I have attached the heatmap I made, and the red arrows show where I want to move the y axis labels. Thanks for the insight!

enter image description here

Linton
  • 45
  • 5
  • 3
    Does this answer your question? [Remove space between plotted data and the axes](https://stackoverflow.com/questions/22945651/remove-space-between-plotted-data-and-the-axes) – Mojoesque Nov 02 '21 at 15:53
  • Unfortunately this only seems to work with continuous y or x axes. I tried this method, as well as with scale_y_discrete(expand = c(0, 0)) - neither of these worked. – Linton Nov 02 '21 at 15:57
  • 1
    The argument for `expand` takes `expansion` as a wrapper; see the docs for any scale. It should be type-agnostic for any x or y scale. But the fact that you accidentally assigned the y-scale twice, instead of the x once and y once, makes this a typo. I'm voting to close for that reason – camille Nov 02 '21 at 17:12

1 Answers1

0

Using scale_x_discrete(expand = c(0,0)) does the trick. Since you want to reduce the space on the x-axis you need to use this scale and not the one for the y axis.

Mojoesque
  • 1,166
  • 8
  • 15