# Plotting numbers with percentages (dual axis?)

Hi - I'm looking to show counts alongside percentages in a graph. In excel, I would probably put the percents on a dual axis as markers with no line. Not sure what the best way to go about this in ggplot2 would be, or if someone can think of a better way to display data in two different formats on the same graph. Here's the code I'm using, thanks for the assistance!

``````library(tidyverse)
library(reshape2)

mtcars <- mtcars
mtcars\$carnames <- rownames(mtcars)
rownames(mtcars) <- 1:nrow(mtcars)
mtcars\$cyl <- as.factor(mtcars\$cyl)

#create dataframe for graph
df <-  mtcars %>%
group_by(cyl) %>%
mutate(unique_cars = n(),
num_manual = sum(am),
percent_manual = (num_manual / unique_cars)*100) %>%
select(cyl, unique_cars, num_manual, percent_manual) %>%
distinct() %>%
melt()

#graph
ggplot(data = df, aes(x = cyl, y = value, fill = variable))+
geom_bar(stat = "identity")
``````

You can create a secondary axis using the `sec.axis` argument in `scale_y_ continuous`. By defining the total number in your `value` column, you can create the percentages:

``````total_value <- sum(df\$value)

#graph
ggplot(data = df, aes(x = cyl, y = value, fill = variable))+
geom_bar(stat = "identity") +
scale_y_continuous(sec.axis = sec_axis(~(./total_value)*100, name = "Percentages"))
``````
3 Likes

Is there a way to refer to the existing `y` data? Rather than having to pre-calculate the total.