-2

I have following dataframe:

col1 col2 col3 col4
Y     N    N    N
Y     N    Y    Y
Y     N    N    Y
Y     N    N    N

I would like to use ggplot to plot a chart with %values written in bar itself.

enter image description here

Community
  • 1
  • 1
hss
  • 317
  • 1
  • 2
  • 13
  • 1
    Reshape your data - *melt*, then *geom_bar*, then see [this post](https://stackoverflow.com/questions/3695497/show-instead-of-counts-in-charts-of-categorical-variables). Show some effort. Possible duplicate. – zx8754 Sep 11 '17 at 11:52
  • 1
    Perhaps you can show us what you have tried, and why it has failed. Then this will read more like a question and less like an order to a contractor. – Axeman Sep 11 '17 at 11:53
  • 1
    [This post](https://stackoverflow.com/questions/12386005/r-stacked-percentage-bar-plot-with-percentage-of-binary-factor-and-labels-with) would also help you. – jazzurro Sep 11 '17 at 12:06

1 Answers1

4

This should do just fine

#your data.frame
df <- read.table(text=
                "col1 col2 col3 col4
                 Y     N    N    N
                 Y     N    Y    Y
                 Y     N    N    Y
                 Y     N    N    N", header=T)
library(reshape2)
df$ID <- 1:length(df)
df <- melt(df, id.vars = "ID") #melting the data.frame into long format
library(ggplot2) #and ploting it
ggplot(df)+
  geom_bar(aes(x=variable, fill=value), stat="count")

For an outcome in percentages you can do

ggplot(df) +
  geom_bar(aes(x=variable, y= (..count..)/sum(..count..), fill=value))
Patrik_P
  • 3,066
  • 3
  • 22
  • 39