ユーザ用ツール

サイト用ツール


ggplot2でタイトルとx軸y軸の設定

ggplot2でタイトルとx軸y軸の設定

初めての医療統計 目次

ggplot2でグラフを描いた後に、タイトルを中央に記載したり、y軸の値の範囲の設定、x軸のラベルの値の変更などについて記載します。

ggplot2でx軸のラベルを変更
2017/12/30 2017/12/31

http://twosquirrel.mints.ne.jp/?p=21665

ソースコード

開発環境

RStudio Cloudのconsole画面(画面左下)で、install.packages(“tidyverse”)を入力して、tidyverseパッケージをインストールした状態とします。

参考:http://twosquirrel.mints.ne.jp/?p=26918

グラフタイトルをグラフ上部中央に記載する

ggplot() +
  ggtitle("Use theme(plot.title = element_text(hjust = 0.5)) to center") +
  theme(plot.title = element_text(hjust = 0.5))

参考:https://codeday.me/jp/qa/20190317/372133.html

x軸の値を変更する

x軸の値が離散値(?)の場合

scale_x_discrete(“Time”, labels = c(“1″=”first”, “2”=”second”, “3”=”third”)

のように用いる。

例)

b <- b + 
  scale_x_discrete("Time", labels = c("Course1" = "preop", "Course2" = "one week", "Course3" = "one month", "Course4" = "three months")) +
  theme(plot.title = element_text(hjust = 0.5), text = element_text(size=20))


https://stackoverflow.com/questions/13297995/changing-font-size-and-direction-of-axes-text-in-ggplot2

x軸の値が連続値の場合

coord_cartesian(ylim = c(0,25)) + 
scale_x_continuous(breaks = seq(0,25,by=5),labels=c(0,5,10,15,20,25))

のような感じで用いる。

例)

b <- b + coord_cartesian(ylim = c(0,25)) + 
scale_x_continuous(breaks = seq(0,25,by=5),labels=c(0,5,10,15,20,25))

ggplot2でグラフのタイトルを真ん中に

b <- b + ggtitle(“New Title”)
b <- b + theme(plot.title = element_text(hjust=0.5))
b <- b + theme(plot.title = element_text(size = 20),
axis.title.x = element_text(size= 20),
axis.title.y = element_text(size= 20),
axis.text.x = element_text(size= 20),
axis.text.y = element_text(size= 20))

軸のラベルの書き換え

# y軸のラベルの書き換え
labs(y="Length")

グループによって少しだけx軸方向にずらす

pd <- position_dodge(0.1)

ggplot(tgc, aes(x=dose, y=len, colour=supp)) + geom_errorbar(aes(ymin=len-se, ymax=len+se), width=.1, position=pd) + geom_line(position=pd) + geom_point(position=pd)

のように使う。

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

リンク

Rでグラフを描くための初心者向けのおすすめの本

初めての方には、以下の本が非常にお勧めです。

上記の本でggplot2に慣れたら、以下の本でデータ整理について学んでみるのがお勧めです。

リンク

ggplot2でタイトルとx軸y軸の設定.txt · 最終更新: 2020/08/12 by adash333

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki