Change Y-Axis to Percentage Points in ggplot2 Barplot in R
In this article, we will discuss how to change the Y-axis to percentage using the ggplot2 bar plot in R Programming Language.
First, you need to install the ggplot2 package if it is not previously installed in R Studio. To install and load write the below command in R Console :
For creating a simple bar plot we will use the function geom_bar( ).
geom_bar(stat, fill, color, width)
- stat : Set the stat parameter to identify the mode.
- fill : Represents color inside the bars.
- color : Represents color of outlines of the bars.
- width : Represents width of the bars.
First, we will create a Data Frame which has two vectors “letter” and “probability” and stores it in a variable prob.
Let’s create a simple bar plot.
Changing Y-axis to Percentage
Some important keywords used are :
- accuracy: The precision value to which a number is round to.
- scale: It is used for scaling the data. A scaling factor is multiplied with the original data value.
- labels: It is used to assign labels.
The function used is scale_y_continuous( ) which is a default scale in “y-aesthetics” in the library ggplot2. Since we need to add percentages in the labels of the Y-axis, the keyword “labels” is used.
Now use scales: : percent to convert the y-axis labels into a percentage. This will scale the y-axis data from decimal to percentage. It simply multiplies the value by 100. The scaling factor is 100.
In the above code add :
In older versions of R, using the above code you may get the percentage values having one digit after the decimal in the Y-axis as shown in the above example. In such a case, we will use the function percent_format( ) to modify the accuracy of the percentage labels in Y-axis. It is basically used to assign the precision value in order to round it.
Now, modify the above code into :