ggplot changing colors of bar plot

2019-07-29 10:54发布

问题:

I came across this R script that use ggplot:

dat <- read.table(text = "A   B   C   D   E   F    G
1 480 780 431 295 670 360  190
2 720 350 377 255 340 615  345
3 460 480 179 560  60 735 1260
4 220 240 876 789 820 100   75", header = TRUE)

library(reshape2)

dat$row <- seq_len(nrow(dat))
dat2 <- melt(dat, id.vars = "row")

library(ggplot2)

ggplot(dat2, aes(x=variable, y=value, fill=row)) + 
  geom_bar(stat="identity") +
  xlab("\nType") +
  ylab("Time\n") +
  guides(fill=FALSE) +
  theme_bw()

That was what I've been looking for. However, I could not:

  1. change the default colours (for example, I tried to use the "RdYlGn" palette)
  2. convert the raw values to frequencies.

    Any suggestions?

回答1:

You could try this:

library(reshape2)
library(dplyr)
library(ggplot2)

library(ggplot2)

dat%>%
  melt(id.vars = "row",variable.name = "grp")%>%
  group_by(grp)%>%
  mutate(tot=sum(value), fq=value/tot)%>%
  ggplot(aes(x=grp,y=fq,fill=row,label = sprintf("%.2f%%", fq*100)))+
  geom_bar(stat = "identity")+
  geom_text(size = 3, position = position_stack(vjust = 0.5))+
  xlab("\nType") +
  ylab("Time\n") +
  guides(fill=FALSE) +
  scale_fill_distiller(palette = "RdYlGn")+
  theme_bw()



标签: r ggplot2