Custom Y tick text in R

Viewed 31

I have a dataset structure(list(ValueName = c("Value 11", "Value 14", "Value 13", "Value 12", "Value 10", "Value 1", "Value 5", "Value 9", "Value 4", "Value 7", "Value 8", "Value 3", "Value 15", "Value 2", "Value 6", "Value 11", "Value 14", "Value 13", "Value 12", "Value 10", "Value 1", "Value 5", "Value 9", "Value 4", "Value 7", "Value 8", "Value 3", "Value 15", "Value 2", "Value 6", "Value 11", "Value 14", "Value 13", "Value 12", "Value 10", "Value 1", "Value 5", "Value 9", "Value 4", "Value 7", "Value 8", "Value 3", "Value 15", "Value 2", "Value 6" ), plotOrder = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L), Response = c("A1", "A1", "A1", "A1", "A1", "A1", "A1", "A1", "A1", "A1", "A1", "A1", "A1", "A1", "A1", "A2", "A2", "A2", "A2", "A2", "A2", "A2", "A2", "A2", "A2", "A2", "A2", "A2", "A2", "A2", "A3", "A3", "A3", "A3", "A3", "A3", "A3", "A3", "A3", "A3", "A3", "A3", "A3", "A3", "A3"), Percent = c(86.5, 85.3, 84.5, 83.2, 81, 79.5, 77, 76.7, 71, 66.2, 64.5, 60.5, 59.6, 57.2, 53.2, 9.9, 9.4, 10.2, 9.9, 11.8, 14.7, 13.9, 13.5, 15.1, 16.1, 21.3, 21.3, 26.6, 19.8, 18.5, 3.6, 5.3, 5.3, 6.9, 7.2, 5.8, 9, 9.8, 13.9, 17.7, 14.1, 18.2, 13.8, 22.9, 28.2)), .Names = c("ValueName", "plotOrder", "Response", "Percent"), row.names = c(NA, -45L), class = c("tbl_df", "tbl", "data.frame")) which produces the following:

enter image description here

But I want to change the X and Y tick text according to a custom value.

for example like the following

enter image description here

Is there any ggplot function to do that? I have looked everywhere but couldn't find anything.

2 Answers

You may try(I filtered and used four Values)

install.packages("ggh4x")
df %>%
  filter(ValueName %in% c("Value 9", "Value 8", "Value 7", "Value 6")) %>%
  ggplot(aes(Percent, ValueName, fill = Response)) +
  geom_col() + scale_y_discrete(labels = c("So On", "Comprehensive", "Clear", "Good")) +
  guides(
    y.sec = ggh4x::guide_axis_manual(
      labels = ~ c("So On", "Incomprehensive", "Unclear", "Bad")
    )
  )

enter image description here

Similar to the approach by @Park but using "just" ggplot2 you could achieve your desired result via a secondary or duplicated axis where I use named vectors of labels. However, this requires to switch to a continuous y scale and to map your plotOrder column directly on y.

library(ggplot2)

labels <- unique(df$ValueName)
names(labels) <- unique(df$plotOrder)
labels2 <- labels

labels[1:2] <- c("Good", "Clear")
labels2[1:2] <- c("Bad", "Unclear")

ggplot(df, aes(Percent, plotOrder, fill = Response)) +
  geom_col(orientation = "y") +
  scale_y_continuous(breaks = unique(df$plotOrder), labels = labels, sec.axis = dup_axis(labels = labels2))

Related