In this tutorial, we will learn how to format x or y-axis so that we have dollar symbol in a plot made with ggplot2 in R.
Let us create a dataframe with salary education information for developers using the StackOverflow survey results. We first create two lists; one for education and the second for salary.
education <- c("Bachelor's", "Less than Bachelor's", "Master's","PhD","Professional") salary <- c(110000,105000,126000,144200,95967)
We create a tibble using the two lists with tibble() function.
df <- tibble(Education=education, Salary=salary) df ## # A tibble: 5 x 2 ## Education Salary ## <chr> <dbl> ## 1 Bachelor's 110000 ## 2 Less than Bachelor's 105000 ## 3 Master's 126000 ## 4 PhD 144200 ## 5 Professional 95967
Let us make a simple bar plot with geom_col() in ggplot2.
df %>% ggplot(aes(x=Education, y=Salary)) + geom_col()
In the barplot, height of bars represent salary for each education category.
Note that on y-axis we have the salary as numbers. Instead, sometimes you would like to have the y-axis with dollars. We can use the R Package scales to format with dollar symbol.
We can do that by specifying scale_y_continuous() with labels=scales::dollar_format()
df %>% ggplot(aes(x=Education, y=Salary)) + geom_col()+ scale_y_continuous(labels=scales::dollar_format())
Now, we get a bar plot with y-axis formatted with dollars.