使用ggplot2命令时,只需将“CoOc”转换为数字(x=as.numeric(CoOc)),然后进行绘图。
library(tidyverse)
# Fake data
Sims <- seq(1,100,1)
CoOc <- sample(90:140, 100, replace = TRUE)
Out <- sample(c("A Wins", "B Wins", "Tie"), 100, replace = TRUE)
df <- data.frame(cbind(Sims, CoOc, Out))
# Ordering data for stacked histogram
df2 <- df %>%
group_by(CoOc, Out) %>% # Grouping by CoOc for the x-axis ordering, and then for Out to get outcome (A Wins, B Wins, Tie) grouped together
summarize(Counts = n())
# Plotting
ggplot(df2)+
geom_bar(aes(fill = Out, y = Counts, x = as.numeric(CoOc)),
position = "stack", stat = "identity")+
labs(title="Example",
x="CoOc",
y="Num")+
scale_fill_manual(name = "Outcome",
values = c("#AD1457", "#B3E5FC", "#FF9800"))+
theme_bw()+
theme(panel.border = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.line = element_line(colour = "white"),
plot.caption.position = "plot",
plot.caption = element_text(hjust = 0))