Reputation: 25
here's my code:
library(ggplot2)
duration <- c(270,1740,90,30,180,180, 20, 300, 150)
no <- c(1,1,1,1,1,1, 2, 2, 2)
class <- c("7","1","2","1","2","3","1","3","2")
data <- cbind(duration, no, class)
data <- data.frame(data)
p <- ggplot(data, aes(x=no, y=duration, fill=class)) + geom_bar(stat="identity")
I want to make a plot that just shows the data values as they are. For example, from the bottom, no1, class 7, duration 270 and then no1, class 1, duration 1740 and then no1, class 2, duration 90, and no1, class 1 again, duration 30...
However, this bar plot automatically summarizes depending on "class". Or when I tried to set levels..still the order is messed up and
data$Legend1 <- factor(data$Legend1, level=c("7","1","2","1","2","3"))
got a warning. Absolutely it wasn't a good way to solve this problem since levels are different between all "no".
In `levels<-`(`*tmp*`, value = if (nl == nL) as.character(labels) else paste0(labels, : duplicated levels in factors are deprecated
This is my bar plot after level set:
Since I'm a newbie, my question can be more of basic, I'm troubling with this matter for a week though. Please help me. Thanks in advance.
Upvotes: 1
Views: 151
Reputation: 513
just leave the cbind out of your code. You don't need that.
library(ggplot2)
duration <- c(270,1740,90,30,180,180, 20, 300, 150)
no <- c(1,1,1,1,1,1, 2, 2, 2)
class <- c("7","1","2","1","2","3","1","3","2")
data <- data.frame(duration, no, class)
ggplot(data, aes(x=no, y=duration, fill=class)) + geom_bar(stat="identity")
should do what you want it to do!
Upvotes: 0
Reputation: 29095
Some points to note:
Issue 1. duration
in your dataset is a factor, not a number. You can skip cbind()
& create your data frame directly from the vectors to avoid that:
duration <- c(270,1740,90,30,180,180, 20, 300, 150)
no <- c(1,1,1,1,1,1, 2, 2, 2)
class <- c("7","1","2","1","2","3","1","3","2")
data <- data.frame(duration, no, class)
> str(data)
'data.frame': 9 obs. of 3 variables:
$ duration: num 270 1740 90 30 180 180 20 300 150
$ no : num 1 1 1 1 1 1 2 2 2
$ class : Factor w/ 4 levels "1","2","3","7": 4 1 2 1 2 3 1 3 2
Issue 2. The stacked bars are automatically grouped according to the fill colours. You can avoid that by specifying the group by row number:
library(dplyr)
ggplot(data %>% group_by(no) %>% mutate(rowid = rev(row_number())),
aes(x=no, y=duration, group = rowid, fill=class)) +
geom_bar(stat="identity")
(Side note: you can use geom_col()
instead of geom_bar(stat="identity")
too.)
Upvotes: 4