Amir Valizadeh
Amir Valizadeh

Reputation: 73

ggplot having two stacks of x axis text

So my current plot looks like this: enter image description here

But I want to add one or two other series of text to the plot to look something like this:

enter image description here

Is that even possible to do such a thing using ggplot or should I go after another package?

Update: Here is the code for my current plot:

ggplot() + geom_col(data = s, aes(x = V1, y = V3, fill = V3), show.legend = F) + 
coord_flip() + 
labs(x = "", y = "") + 
scale_fill_gradient(low = "yellow", high="darkgreen") + 
theme(axis.text.y = element_text(vjust = 0, hjust = 0), plot.margin = margin(1, 0.3, 0.1, 0.3, "cm"), panel.background = element_rect(fill = 'white', colour = 'white'), axis.ticks.y = element_blank()) + ylim(0, 6)

and here is some fake data:

1  a  b  6  7
2  c  d  8  9
3  g  f  5  4
4  f  n  3  2

and here is the output of the real data:

structure(list(V1 = c("regulation of locomotion", "regulation of cell migration", 
"skin development", "negative regulation of biological process", 
"cell adhesion", "response to oxygen-containing compound"), V2 = c(7.74e-05, 
0.000143, 0.000165, 0.000176, 0.00019, 0.00019), V3 = c(4.111259039, 
3.844663963, 3.782516056, 3.754487332, 3.721246399, 3.721246399
)), row.names = c(NA, 6L), class = "data.frame")

Upvotes: 0

Views: 73

Answers (1)

stefan
stefan

Reputation: 124183

In case of just one column one of the easiest options would be to add the second column for your axis text via a geom_text layer like so. You only have to make sure to set the right size and color as for the axis text:

library(ggplot2)

ggplot(data = s) +
  geom_col(aes(x = V3, y = V1, fill = V3), show.legend = F) +
  geom_text(aes(x = -1, y = V1, label = scales::label_scientific()(V2)),
    hjust = 0, size = .8 * 11 / .pt, vjust = 0, color = "grey30"
  ) +
  labs(x = "", y = "") +
  scale_fill_gradient(low = "yellow", high = "darkgreen") +
  theme(
    axis.text.y = element_text(vjust = 0, hjust = 0),
    plot.margin = margin(1, 0.3, 0.1, 0.3, "cm"),
    panel.background = element_rect(fill = "white", colour = "white"),
    axis.ticks.y = element_blank()
  ) +
  xlim(-1, 6)

Upvotes: 1

Related Questions