zoukankan      html  css  js  c++  java
  • R数据可视化手册学习——条形图

     1. 绘制简单条形图

    # 使用ggplot2和gcookbook 
    library(ggplot2); library(gcookbook)
    
    g <- ggplot(data = pg_mean, aes(x = group, y = weight)) +
      geom_bar(stat = "identity", fill = "green", color = "black") # fill表示填充颜色,color表示边线框颜色
    
    g

    2. 绘制簇状条形图

    # 使用ggplot2和gcookbook的cabbage_exp数据集
    library(ggplot2); library(gcookbook)
    
    
    g <- ggplot(data = cabbage_exp, aes(x = Date, y = Weight, fill = Cultivar)) +
      # width表示每个条形的宽度(默认是0.9, 当为0.9时,可以省略width = 0.9), position表示组内条形的间距(position = position_dodge(0.9)可以替换成position = "dodge")  
      #geom_bar(stat = "identity",width = 0.9, position = position_dodge(0.9)) 
      # 上面和下面等价
      geom_bar(stat = "identity", position = "dodge")
    
    g

    3. 条形图填充颜色

    # 使用ggplot2和gcookboo的数据集upc
    library(ggplot2); library(gcookbook)
    
    upc <- subset(uspopchange, rank(Change) > 40)
    
    # 使用scale_fill_manual()对颜色进行填充
    g <- ggplot(data = upc, aes(x = Abb, y = Change, fill = Region)) +
      geom_bar(stat = "identity") +
      scale_fill_manual(values = c("#5ED5D1", "#FF6E97"))
    
    g

    4. 修改坐标名称、标题、添加数据标签

    # 使用ggplot2和gcookbook的数据集cabbage
    library(ggplot2); library(gcookbook)
    
    # 添加标题、X轴、Y轴
    
    # 方法1(通过ggtitle、xlab、ylab)
    g <- ggplot(data = cabbage_exp, aes(x = interaction(Date, Cultivar), y = Weight)) +
      geom_bar(stat = "identity") +
      ggtitle(label = "数据展示") +
      xlab(label = "日期, 品种") +
      ylab(label = "重量") +
      theme(plot.title = element_text(hjust = 0.5)) # 标题居中
    
    g
    
    # =====================================
    
    # 方法2(通过labs)
    g <- ggplot(data = cabbage_exp, aes(x = interaction(Date, Cultivar), y = Weight)) +
      geom_bar(stat = "identity") + 
      labs(title = "数据展示", x = "日期, 品种", y = "重量") +
      theme(plot.title = element_text(hjust = 0.5)) # 标题居中
    
    g
    
    
    # =====================================
    
    # 添加数据标签
    g <- ggplot(data = cabbage_exp, aes(x = interaction(Date, Cultivar), y = Weight)) +
      geom_bar(stat = "identity") + 
      labs(title = "数据展示", x = "日期, 品种", y = "重量") +
      theme(plot.title = element_text(hjust = 0.5)) + # 标题居中
      geom_text(aes(label = Weight), vjust = 1.5) # 添加数据标签,并设置位置
    
    g

     

  • 相关阅读:
    编写JS代码的“use strict”严格模式及代码压缩知识
    开发网站要从用户的角度出发!
    你好,世界
    JavaScript的几种函数的结构形式
    JavaScript功能检测技术和函数构造
    android打造万能的适配器
    C语言第二次博客作业分支结构
    C语言第三次博客作业单层循环结构
    C语言第一次博客作业——输入输出格式
    C语言第四次博客作业嵌套循环
  • 原文地址:https://www.cnblogs.com/xiaomingzaixian/p/9834998.html
Copyright © 2011-2022 走看看