Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to achieve an absolute percentage scale in ggplot?

Tags:

r

ggplot2

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)

like image 924
etnobal Avatar asked Nov 14 '19 03:11

etnobal


People also ask

How to display percentages on histogram in ggplot2?

How to Display Percentages on Histogram in ggplot2 You can use the following basic syntax to display percentages on the y-axis of a histogram in ggplot2: library(ggplot2) library(scales) #create histogram with percentages ggplot (data, aes(x = factor(team))) + geom_bar (aes(y = (..count..)/sum(..count..))) + scale_y_continuous (labels=percent)

How to visualize decimals in ggplot2?

We can make the visualization as follows. By setting the labels in ggplot2’s scale_y_continuous () function, I can process all the values through a function that turns every value into a percentage. But there is an easier way, using the scales library, by setting the accuracy parameter, you can control how many decimals you would like to show.

How to control the percentage of a label in a graph?

This can be controlled by the scale parameter. However, scale_y_continuous () expects a function as input for its labels parameter not the actual labels itself. Thus, using percent () is not an option anymore.

How do I use break formatting in ggplot2?

Load the package scales to access break formatting functions. Note that, since ggplot2 v2.0.0, date and datetime scales now have date_breaks, date_minor_breaks and date_labels arguments so that you never need to use the long scales::date_breaks () or scales::date_format ().


1 Answers

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

like image 177
rrs Avatar answered Nov 08 '22 16:11

rrs