Skip to content

Conditional axis.text to change font size and font face creates unwanted margin #3739

@tjebo

Description

@tjebo

This issue was raised yesterday in this Stackoverflow thread

This happens not only when using ifelse(), but also when manually changing the fonts, e.g. with a named vector.

In my reprex, I used coord_flip, because this was originally shown by the OP in SO, but the same applies without coord_flip (albeit not that obvious), and also with axis.text.x

The weird thing to me is that this indeed seems only to happen with font size and font family.

library(ggplot2)

ggplot(iris, aes(Species, Petal.Length)) + 
  theme(axis.text.y = element_text(family = ifelse(levels(iris$Species)=="setosa","sans","mono"))) +
  coord_flip()

This also happens without ifelse

library(tidyverse)

ggplot(iris, aes(Species, Petal.Length)) + 
  theme(axis.text.y = element_text(size = c(setosa = 10, virginica = 20, versicolor = 20))) +
  coord_flip()

Adding margin helps, but only with specified units:

ggplot(iris, aes(Species, Petal.Length)) + 
  theme(axis.text.y = element_text(family = ifelse(levels(iris$Species)=="setosa","sans","mono"),
                                   margin = margin(r = -2, l = 0.8, unit = 'in'))) +
  coord_flip()

Created on 2020-01-16 by the reprex package (v0.3.0)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions