3

This is an extension of the already discussed question (I am copying the perfect data example and solution by jakub from https://stackoverflow.com/a/18162330 )

Data:

raw <- read.csv("http://pastebin.com/raw.php?i=L8cEKcxS",sep=",")
raw[,2]<-factor(raw[,2],levels=c("Verygood","Bad","Good","VeryGood"),ordered=FALSE)
raw[,3]<-factor(raw[,3],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,4]<-factor(raw[,4],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw=raw[,c(2,3,4)]
freq=table(col(raw), as.matrix(raw)) # get the counts of each factor level

ggplot + mutliple grouping bar

Names=c("Food","Music","People")     # create list of names
data=data.frame(cbind(freq),Names)   # combine them into a data frame
data=data[,c(5,3,1,2,4)]             # sort columns
# melt the data frame for plotting
data.m <- melt(data, id.vars='Names')
# plot everything
ggplot(data.m, aes(Names, value)) +
geom_bar(aes(fill = variable), position = "dodge", stat="identity")

The only addition I am struggling to make is to add a fitted line (third degree polynomial) to show the trend for each category as variable changes from "very bad" to "very good"

image with desired fitted line

Plotting the trend seems to be an issue.

Michael Harper
  • 14,721
  • 2
  • 60
  • 84
J.Julian
  • 68
  • 6
  • 1
    To plot the trend by category you probably want to use a facet which separates the categories so the trend line calculates separately for each group: `ggplot(data.m, aes(variable, value)) + geom_bar(aes(fill = variable), position = "dodge", stat="identity")+facet_wrap(~Names)`. Then you just need to define your trend line – Mako212 Mar 06 '18 at 07:26
  • 3
    Agreed with @Mako212, but you no longer need dodging. Use e.g. `ggplot(data.m, aes(variable, value)) + geom_bar(aes(fill = variable), position = "dodge", stat="identity") + facet_grid(~Names) + geom_smooth(aes(group = 1))`. Will not look good with few categories. – Axeman Mar 06 '18 at 08:52

0 Answers0