ggplot改变条形图的颜色 [英] ggplot changing colors of bar plot

查看:1415
本文介绍了ggplot改变条形图的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  dat<  -  read.table(text =ABCDEFG 
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 = 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 \\\
)+
guides(fill = FALSE)+
theme_bw()

这就是我一直在寻找的东西。但是,我无法:


  1. 更改默认颜色(例如,我尝试使用RdYlGn
    调色板)

  2. 将原始值转换为频率。

    有什么建议?

  3. $ b $

    解决方案

    code> library(reshape2)
    library(dplyr)
    library(ggplot2)

    library(ggplot2)

      dat%>%
    melt(id.vars =row ,变量。名称=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(\\\
    Type)+
    ylab(Time \\\
    )+
    指南(fill = FALSE)+
    scale_fill_distiller(palette =RdYlGn)+
    theme_bw()


    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?

    解决方案

    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()
    

    这篇关于ggplot改变条形图的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆