ユーザ用ツール

サイト用ツール


ggplot2で論文用の白黒折れ線グラフ

文書の過去の版を表示しています。


ggplot2で論文用の白黒折れ線グラフ

ggplot2(tidyverse)では、カラーのきれいなグラフを出力してくれるのはありがたいのですが、論文用には白黒のグラフを作成したい場合が多いです。

基本的には、ggplot()+theme_set(theme_classic())を用いるのですが、具体的な方法を記載させていただきたいと思います。

1.サマリー作成用の関数の定義

ggplot2()でグラフを記載する前に、データを整理する必要があります。

Plotting means and error bars (ggplot2)

http://www.cookbook-r.com/Graphs/Plotting_means_and_error_bars_(ggplot2)/

summarySE <- function(data=NULL, measurevar, groupvars=NULL, na.rm=FALSE,
                      conf.interval=.95, .drop=TRUE) {
    library(plyr)

    # New version of length which can handle NA's: if na.rm==T, don't count them
    length2 <- function (x, na.rm=FALSE) {
        if (na.rm) sum(!is.na(x))
        else       length(x)
    }

    # This does the summary. For each group's data frame, return a vector with
    # N, mean, and sd
    datac <- ddply(data, groupvars, .drop=.drop,
      .fun = function(xx, col) {
        c(N    = length2(xx[[col]], na.rm=na.rm),
          mean = mean   (xx[[col]], na.rm=na.rm),
          sd   = sd     (xx[[col]], na.rm=na.rm)
        )
      },
      measurevar
    )

    # Rename the "mean" column    
    datac <- rename(datac, c("mean" = measurevar))

    datac$se <- datac$sd / sqrt(datac$N)  # Calculate standard error of the mean

    # Confidence interval multiplier for standard error
    # Calculate t-statistic for confidence interval: 
    # e.g., if conf.interval is .95, use .975 (above/below), and use df=N-1
    ciMult <- qt(conf.interval/2 + .5, datac$N-1)
    datac$ci <- datac$se * ciMult

    return(datac)
}

2.白黒の折れ線グラフの作成

library(tidyverse)

tg <- ToothGrowth
tgc <- summarySE(tg, measurevar="len", groupvars=c("supp","dose"))

pd <- position_dodge(0.1) # move them .05 to the left and right

ggplot(tgc, aes(x=dose, y=len, shape=supp)) +
    theme_set(theme_classic()) +
    geom_point(size=4, position=pd) +
    geom_errorbar(aes(ymin=len-se, ymax=len+se), width=.1, position=pd) +
    geom_line(aes(linetype = supp), position=pd)

以下のようなグラフが出力されます。

3.グラフをpngファイルで出力

以下のように、ggsave()関数で、グラフをpngファイルで出力することができます。

グラフを出力する方法としては、RmdファイルをKnit(htmlファイルなどに変換すること)してから、htmlファイル上の画像を右クリックして保存することでも、保存することができます。

library(tidyverse)

p0 = ggplot(mpg, aes(x = displ, y = cty))
p1 = p0 + geom_point()
p2 = p1 + theme_classic(base_size = 20, base_family = "Helvetica")
p3 = p2 + stat_smooth(method = lm, formula = y ~ log(x))

ggsave("mpg-displ-cty.png", p3, width = 4, height = 4, dpi=300)

Rmdファイルと同じフォルダに、以下のようなgraph.pngが保存されます。

エラーバーを片方だけにつける

下記リンク先によりますと、

1. geom_errorbar()でwidth=0のエラーバーを作成
2. geom_segment()で片方だけエラーバーの横線を追加

という流れになります。

geom_segment()でエラーバーのxの始点と終点を指定するときに、

横軸が数字であれば、as.numeric(key)-0.1のように指定する

横軸が文字(00pre, 1month, 2month, 3monthなど)であれば、
keyを0,1,2,3などに置き換えてから(csvファイルを修正しておいてもよいかもしれません)、
as.numeric()で数値に変更しておく。

ところが少し難しいポイントとなります。

pd <- position_dodge(0.1) # move them .05 to the left and right

ggplot(xc, aes(x=key, y=value, shape=DM, group = DM)) +
    theme_set(theme_classic()) +
    geom_point(size=4) +
    #errorbar without caps
    geom_errorbar(data=with(xc,xc[which(DM=='D'),]),
            aes(ymin = value, ymax = value+se),width=0) +
    geom_errorbar(data=with(xc,xc[which(DM=='N'),]),
            aes(ymin = value-se, ymax = value),width=0) +
    geom_line(aes(linetype = DM), position=pd) +
    #geom_segment for caps
    geom_segment(data=with(xc,xc[which(DM=='D'),]),
            aes(y=value+se,yend=value+se,x= as.numeric(substr(key, 7, 7))-0.1,xend= as.numeric(substr(key, 7, 7))+0.1)) +
    geom_segment(data=with(xc,xc[which(DM=='N'),]),
            aes(y=value-se,yend=value-se,x= as.numeric(substr(key, 7, 7))-0.1,xend= as.numeric(substr(key, 7, 7))+0.1)) +
    ylim(230, 300) +
    ggtitle("Figure 3") +
    theme(plot.title = element_text(hjust = 0.5))

https://stackoverflow.com/questions/44194700/selecting-direction-of-multiple-error-bars-in-a-line-plot

リンク

リンク(英語)

ggplot2で論文用の白黒折れ線グラフ.1534046741.txt.gz · 最終更新: 2018/10/07 (外部編集)

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki