0

I'm trying to draw a grouped bar plot in r

Here is my code:

xtable <- xtabs(~ view + grade, data=hs)

xtable

barplot(xtable, beside = T, legend.text = T)

library(reshape2)
data.m <- melt(xtable, id.vars='view')

data.m
# plot
ggplot(data.m, aes(grade, value)) + geom_bar(aes(fill = view), 
   width = 0.4, position = "dodge", stat="identity") +  
   theme(legend.position="top", legend.title = 
   element_blank(),axis.title.x=element_blank(), 
   axis.title.y=element_blank())

View and grade are two properties of homes sold. Grade is a value between 0 to 13 showing the rank of a home, and view is 0 to 4 showing how good is the view of the home.

The usual barplot command in r works oaky. However, I liked a ggplot for it. I followed the answer of similar questions, but I get a stacked bar instead of a grouped one. Also, how can I generate a segmented bar plot and spine plot using the same data?

enter image description here

Ahmad
  • 8,811
  • 11
  • 76
  • 141

1 Answers1

1

Your code considers view as continuous, where it is not. Convert it to factor.

library(ggplot2)
library(reshape2)

hs <- read.csv(file = file.choose())

xtable <- xtabs(formula = (~ view + grade),
                data = hs)

data.m <- melt(data = xtable,
               id.vars='view')

ggplot(data = data.m,
       mapping = aes(x = grade,
                     y = value)) +
  geom_bar(mapping = aes(fill = factor(x = view)),
           position = "dodge",
           stat="identity")

This generates the following, which you can modify later to make it look nicer.

side_by_side_barplot

yarnabrina
  • 1,561
  • 1
  • 10
  • 30