djq
djq

Reputation: 15286

Help understanding how to make a bar chart using ggplot2

I'm trying to use the bar_geom function of ggplot2, but I can't understand how to use it. I've made a small sample of my code to show what I am trying to do:

library(ggplot2)

# sample data
sampleData = data.frame( 
 v1=c('a','b','c','d','e', 'f','g', 'h', 'i','j'), 
 v2=c(1:10)     
)    
sampleData$Names = data.frame( Names = paste(sampleData$v1, sampleData$v2, sep="") )    
sampleData$Values = c(1:10)

# make plot
x = sampleData$Values
y = sampleData$Names 

qplot(      
    x, y, data = sampleData,
    geom="bar"  
)

I want sampleData$Names to be on the x-axis of my graph, labeling each bar and and sampleData$Values to scale the bar height. I want the y-axis to be specified as a range. I realize that I don't understand how ggplot2 functions as this small example does not work, yet my other example is generating a plot but I cannot specify a y-range as it considers the variables to be categorical.

Upvotes: 1

Views: 748

Answers (2)

Roman Luštrik
Roman Luštrik

Reputation: 70623

Another quick plot with the same results as pchalasani got is with

qplot(v1, v2, geom = "bar", stat = "identity", data = sampleData)

Pay special attention to the argument stat.

Upvotes: 0

Prasad Chalasani
Prasad Chalasani

Reputation: 20282

qplot expects column names within the sampleData data-frame, and your code where you set the 'Names' column to a data-frame is also strange. The following simpler version works:

sampleData = data.frame( 
 v1=c('a','b','c','d','e', 'f','g', 'h', 'i','j'), 
 v2=c(1:10)     
)

sampleData = transform( sampleData, Names = paste(v1, v2, sep=''))

qplot(   Names, v2, data = sampleData,    geom="bar"  )

alt text

Upvotes: 2

Related Questions