2

How can we set the attribute of one label not all labes on axis using ggplot2. For example:

df <- data.frame(x=letters[1:5],y=1:5)
ggplot(df,aes(x,y))+geom_bar(stat = "identity")

figure

How can we make c bigger than other label like a,b,d,e.

Aaron
  • 69
  • 5
  • 1
    Check out [`{ggtext}`](https://wilkelab.org/ggtext/articles/introduction.html). This package allows custom formatting of axis labels (and many other things too). – Dan Adams Dec 29 '21 at 14:31
  • Without an external package, `ggplot2` does not really allow theming of the axis labels in that way. Even if you set up a second axis, the format is shared between the primary and secondary. I think `ggtext` is likely the best (only?) way to go for that. – r2evans Dec 29 '21 at 14:38
  • Also https://stackoverflow.com/q/47934253/5325862 – camille Dec 29 '21 at 15:05

1 Answers1

2

There are two options to do this. The first one is to use the {ggtext} package to style the label using html tags.

library(ggplot2)
library(ggtext)

df <- data.frame(x = letters[1:5], y = 1:5)

ggplot(df, aes(x, y)) +
  geom_col() +
  scale_x_discrete(
    labels = c("a", "b", "<span style='font-size:16pt'>c</span>", "d", "e")
  ) +
  theme(
    axis.text.x.bottom = element_markdown()
  )

The second option is with vanilla ggplot2, but is discouraged since the internal implementation is not guaranteed to be vectorised such that this will continue to work (as indicated by the warning).

ggplot(df, aes(x, y)) + 
  geom_col() +
  theme(
    axis.text.x.bottom = element_text(size = c(8.8, 8.8, 16, 8.8, 8.8))
  )
#> Warning: Vectorized input to `element_text()` is not officially supported.
#> Results may be unexpected or may change in future versions of ggplot2.

Created on 2021-12-29 by the reprex package (v2.0.1)

teunbrand
  • 33,645
  • 4
  • 37
  • 63