14.8 C
London
Tuesday, July 2, 2024
HomeTidyverse in Rggplot2 in RHow to Convert Axis in ggplot2 to Percentage Scale

How to Convert Axis in ggplot2 to Percentage Scale

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

You can use the following basic syntax to convert an axis in ggplot2 to a percentage scale:

+ scale_y_continuous(labels = scales::percent)

The following example show how to use this syntax in practice.

Example: Convert Axis in ggplot2 to Percentage Scale

Suppose we have the following data frame in R that shows the percentage of items that were returned at four different stores:

#create data frame
df frame(store=c('A', 'B', 'C', 'D'),
                 returns=c(.14, .08, .22, .11))

#view data frame
df

  store returns
1     A    0.14
2     B    0.08
3     C    0.22
4     D    0.11

Now suppose we create a bar chart in ggplot2 to visualize the return percentages for each store:

library(ggplot2)

#create bar chart
ggplot(data=df, aes(x=store, y=returns)) +
  geom_bar(stat='identity')

By default, ggplot2 displays the values on the y-axis using decimals.

However, we can use the following syntax to change the y-axis to a percentage scale:

library(ggplot2)

#create bar chart with percentages on y-axis
ggplot(data=df, aes(x=store, y=returns)) +
  geom_bar(stat='identity') +
  scale_y_continuous(labels = scales::percent)

The y-axis now has a percentage scale.

By default, one decimal place is shown. However, we can use the accuracy argument to drop the decimal place from the y-axis:

library(ggplot2)

#create bar chart with percentages on y-axis
ggplot(data=df, aes(x=store, y=returns)) +
  geom_bar(stat='identity') +
  scale_y_continuous(labels = scales::percent_format(accuracy=1))

ggplot2 percentage axis

The y-axis is now shown as a percentage without any decimal places.

Additional Resources

The following tutorials explain how to perform other common functions in ggplot2:

How to Remove a Legend in ggplot2
How to Remove Gridlines in ggplot2
How to Rotate Axis Labels in ggplot2

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories