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)
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)
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.
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.
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 ().
The answer is in the comments: use labels = function(x) percent(abs(x))
in scale_y_continuous()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With