博文

ggplot2绘制条形图——bar plot using ggplot2

图片
      在实际应用过程中,学会了用ggplot2绘制条形图。也许是最基本的用法,但是在此记录备忘。       条形图一般用于值大小的比较,或是值之间是否有显著性差异。不涉及值之间的趋势,也不涉及值之间的相关等。       首先是数据格式。可以定义的有:类别(group)、X轴对象(subject / individual)、对象的分组(facet )、Y轴值(value)、标准差或标准误(SD/SE)。数据表格大致如下:       第一列是数据的类别,即想在条形图中显示条形的类别。       第二列是对象/个体的标签名称,即显示在X轴上的对象名称。       第三列、第四列是数据值,这里直接给出了平均值和标准差,有时需要根据现有数据计算出来。       第五列是对象的分组,即将X轴的各个对象/个体自定义进行分组。       下图显示了数据的对应结构:       如何在R中绘制呢? library( ggplot2 ) ## Input the data hetm <- read.table( "data.txt" , head = TRUE )  # Replace the quotes with your own data path ## Plot the graph p <- ggplot( hetm , aes( x = pop , y = mean , fill = het )) + geom_bar( stat = "identity" , color = "black" , position =position_dodge(), lwd = 0 ) + geom_errorbar(aes( ymin = mean - sd , ymax = mean + sd ), width = 0 , lwd = 0.2 , position =position_dodge( 0.9 )) ##...

带误差条的线图 / Line plot with error bar in R

图片
       线图( Line plots) 的生成方法跟点图( Scatter plots) 的产生方法大致相同,这两者都符合“ plot ”这一命令( command) 和其他的定义( customizations),比如定义 axes, box, labels, text, arrows, gridlines, colors, symbols, and legends等 ,用法也相同。         线图和点图的差别在于概念上:如果 x 轴是顺序变量( ordered sequence )或时间变量( time variable) ,而不是预测变量( predictor variable) ,就应该把数据点 连接成线。其他情况下就 不应 把点连接成线。         在线图中,可以将 y 轴的起始点定为 0( 比如说某个指标的程度随着时间变化),但是这点并不是强制的[1]。 基本线图         如仅仅描述某一变量随着时间(或顺序)的变化,则可以用简单线图。比如这里的示例数据如下,我们想绘出March, April, May三个月份的值在随着年份的变化:         R代码可以如下。从所得结果中可以定义线图的各个特征。 data <- read.csv("fail path of example data 1", header=TRUE, sep=";") # Note here sep=";" is used in Mac, different with Windows x <- data$YEAR y3 <- data$T_MAR y4 <- data$T_APR y5 <- data$T_MAY yall <- data.frame(y3, y4, y5) par(mfrow=c(2,3)) matplot(x, yall, type="b", pch=1, col=1:3, main="Pic. 1") matplot(x, yall, type="p", pc...