etnobal
etnobal

Reputation: 111

How to achieve an absolute percentage scale in ggplot?

I am trying to plot positive and negative numbers in a stacked graph using gpplot. This is working fine based on an example I found on this page.

The limits of my graph are -1 and 1, but I want the scale to display the labels as absolute percentages i.e. from 100% on the left over 0% in the center to 100% on the right.

Below minimal examples illustrates that I can get percentage scale labels (labels = percent) or an absolute scale (labels = abs) but I have no idea how to combine them.

Thanks in advance.

library(tidyverse)
library(scales)

x <- tribble(
  ~response, ~count,
  "a",         -0.2,
  "b",         -0.1,
  "c",          0.5,
  "d",          0.2
)

p <- ggplot() +
  geom_bar(data = x,
           aes(x = "", y = count, fill = response),
           position = "stack",
           stat = "identity") +
  coord_flip()

# Percent scale
p + scale_y_continuous(labels = percent, limits = c(-1, 1), expand = c(0.05, 0))

# Absolute scale
p + scale_y_continuous(labels = abs, limits = c(-1, 1), expand = c(0.05, 0))

Created on 2019-11-14 by the reprex package (v0.3.0)

Upvotes: 11

Views: 1663

Answers (2)

rrs
rrs

Reputation: 9893

The answer is in the comments: use labels = function(x) percent(abs(x)) in scale_y_continuous().

Upvotes: 4

Gray
Gray

Reputation: 1388

the positions were changed from stack to dodge. This resulted in cleanly separating the variables at zero while displaying the different count values.

p <- ggplot() +
  geom_bar(data = x %>% filter(count < 0),
      aes(x = "", y = count, fill = response),
      position = "dodge",
      stat = "identity") +
  geom_bar(data = x %>% filter(count >= 0),
  aes(x = "", y = count, fill = response),
  position = "dodge", stat = "identity") +
  coord_flip()

# Percent scale
p + scale_y_continuous(labels = percent, limits = c(-1, 1), expand = c(0.05, 0))

# Absolute scale
p + scale_y_continuous(labels = abs, limits = c(-1, 1), expand = c(0.05, 0)) 

The output is shown somewhere below here.

Great plotting example. Thanks,

enter image description here

Upvotes: -1

Related Questions