Bar chart - ggplot2

2

I have a date-frame with the structure below. I want to make a simple bar chart that lists the "CID" by type (A, B, C, etc ...) with the days of removal and the other with the Meetings.

df <- data.frame(CID = c("A", "A", "B", "C", "C", "Z"),
              AFASTAMENTOS = c(2,3,5,8,9, 12),
              ATENDIMENTOS = c(21, 32, 4, 6, 7, 43),
              stringAsfactors = FALSE )

I tried with ggplot2, making the CID variable a factor:

ggplot(df, aes(CID, y = AFASTAMENTOS)) + geom_bar()

That returned me:     Error: stat_count () must not be used with a and aesthetic.

Thank you very much,

    
asked by anonymous 06.08.2016 / 13:58

2 answers

1

Try this:

df <- data.frame(CID = c("A", "A", "B", "C", "C", "Z"),
                 AFASTAMENTOS = c(2,3,5,8,9, 12),
                 ATENDIMENTOS = c(21, 32, 4, 6, 7, 43),
                 stringsAsFactors = FALSE )
# acumular por CID
dfc<-data.frame(do.call(rbind,by(data = df[,-1],INDICES = df$CID,FUN = colSums)))
dfc$CID<-rownames(dfc)
library(ggplot2)
library(reshape2)
  df.long<-melt(dfc,id.vars="CID") # formatar para long
  ggplot(df.long,aes(x=CID,y=value,fill=factor(variable)))+
    geom_bar(stat="identity",position="dodge")+
    scale_fill_discrete(name="Procedimento")+
    ylab("Número")

    
07.08.2016 / 16:28
0

Your mistake happens because ggplot is designed to work with long bases. Where each line is an observation. In your case the data are already added by CID. Therefore, you need to specify the stat = "identity" argument. By default, ggplot uses count and counts how many rows each of the CIDs have.

My code does the same thing as Robert, but in my view it's more intuitive. We both turned the data into long format to take advantage of the ease of ggplot captioning in that way.

library(tidyr)
library(ggplot2)
df %>%
  gather(Procedimento, Qtd, - CID) %>%
  ggplot(aes(x = CID, y = Qtd, fill = Procedimento)) +
  geom_bar(stat = "identity", position = "dodge")

    
08.08.2016 / 00:10