Home > OS >  ggplot produces is a bar plot of the unique counts rather than count of each unique variable
ggplot produces is a bar plot of the unique counts rather than count of each unique variable

Time:12-01

Here is a reproducible piece of code that exemplifies my problem.

In short, ggplot is graphing the number of instances in the column variable rather than per variable. What I would like is a bar chart that showed how often Lima, Sucre, and Santiago are each present.

library(ggplot2)
library(dplyr)
   
 
Community <c("LIMA","LIMA","SUCRE","SUCRE","SUCRE","SANTIAGO","SANTIAGO","SANTIAGO","SANTIAGO")

df<-data.frame(Community)
df<-rename(df,'a02. Name of Community'=Community)

view(df)

ggplot(data=df, aes('a02. Name of Community'))  
     geom_bar()

Here is the code from my actual problem -

Treating the excel data as input

  outcome<-reactive({ 
    req(input$file1)
    
    inFile <- input$file1 
    dat6<-read_excel(inFile$datapath, sheet =1)
    return(dat6)

Plotting with ggplot from tidyverse

output$plot <- renderPlot({
     Villages <- table(outcome()$'a02. Name of Community')
     ggplot(data=as.data.frame(Villages), aes('a02. Name of Community'))  
     geom_bar()

What the ggplot produces is a bar plot of the unique counts rather than number of times each variable is present.

If I do the plot with plot(), then it works and I get a bar plot with the variables and their count.

The example of the plot() that does work is below.

Villages <- table(outcome()$'a02. Name of Community')
barplot(Villages, main='Participating Communities', horiz=TRUE, cex.names=0.8, las=1,xlab='Count of Evaluations')

CodePudding user response:

It looks like when you try to rename the columns in the examples you change all the variables.

If you do this it works fine:

library(ggplot2)
library(dplyr)


Community<- c("LIMA","LIMA","SUCRE","SUCRE","SUCRE","SANTIAGO","SANTIAGO","SANTIAGO","SANTIAGO")

df<-data.frame(Communitycol=Community)


ggplot(data=df, aes(Communitycol))   geom_bar()

CodePudding user response:

I don't know if I understand your question correctly but I would use the as.factor function

rm(list = ls())

library(ggplot2)
library(dplyr)


Community <-c("LIMA","LIMA","SUCRE","SUCRE","SUCRE","SANTIAGO","SANTIAGO","SANTIAGO","SANTIAGO")

df<-data.frame(Community)
df<-rename(df,'a02. Name of Community'=Community)

df$Community<-as.factor("LIMA","SUCRE","SANTIAGO")

ggplot(data=df, aes(x=Community))  
  geom_bar(aes(fill=Community)) theme_bw()

enter image description here

  • Related