0

I am kind of new to R and I am struggling with ggplot for quite a while now..

I have a dataframe, which looks like this:

x   Freq
1    81
2    36
3    29
4    11
5     9
6    10
7    10
8     4
9     6
>10  49

I want to get a barchart like this:

barplot

But I want the y-axis to show the percentage and the value for Freq on top of the bars.

Javier
  • 732
  • 4
  • 14
  • Please include what you have tried so far in your question. It will give others a better idea of your current level, & give you more targeted assistance. – Z.Lin Jan 10 '19 at 02:13

1 Answers1

0

Here's a solution to your question. Understand that you are a new contributor, welcome! But do try and provide a reproducible example of what you've tried in your future questions.

Create a dataframe first:

set.seed(101)
#create dataframe
df <- data.frame(x = 1:10, Freq = sample(1:100, 10))

There are a number of ways to obtain a percentage column, you can either create it with the 2 methods provided or directly jump into the ggplot2 method:

#create a percent of column
df$Freq_percent <- round(((df$Freq/ sum(df$Freq)) * 100), 2) #Method 1

df

    x Freq Freq_percent
1   1   38         8.94
2   2    5         1.18
3   3   70        16.47
4   4   64        15.06
5   5   24         5.65
6   6   29         6.82
7   7   55        12.94
8   8   32         7.53
9   9   58        13.65
10 10   50        11.76

Method 2: Using dplyr

df <- dplyr::mutate(df, Freq_percent_dplyr = (Freq / sum(Freq))*100) #Method 2

df

    x Freq Freq_percent_dplyr
1   1   38           8.941176
2   2    5           1.176471
3   3   70          16.470588
4   4   64          15.058824
5   5   24           5.647059
6   6   29           6.823529
7   7   55          12.941176
8   8   32           7.529412
9   9   58          13.647059
10 10   50          11.764706

Plotting of Your Bar Chart:

library(ggplot2)
ggplot(df, aes(x=x, y=Freq_percent)) + 
  geom_bar(stat='identity') +
  geom_text(aes(label=paste("Freq:", Freq)), vjust=0) +
  scale_x_continuous(breaks = c(1:10)) + 
  theme_classic()

Plot1

The below code will allow you to paste the frequency variable on top of every bar chart.

geom_text(aes(label=paste("Freq:", Freq)), vjust=0)

Method of Obtaining % for Y-axis without Prior Manipulation of Dataframe:

ggplot(df, aes(x=x, y=Freq)) + 
  geom_bar(stat='identity') + 
  geom_text(aes(label=paste("Freq:", Freq)), vjust=0) +
  scale_y_continuous(labels = scales::percent) + 
  scale_x_continuous(breaks = c(1:10)) + 
  theme_classic()

Plot2

The code below is what you are looking for to make y-axis into percentages

scale_y_continuous(labels = scales::percent) +

Javier
  • 732
  • 4
  • 14
  • Thank you, that helped me a lot. Im sorry for my weak explanation for this threat.I will try to make better post or questions next time. – Axeleration Jan 11 '19 at 03:27
  • @Axeleration appreciate it if you could upvote and accept it as correct answer if it helps you. thanks! – Javier Jan 11 '19 at 05:35