2015-10-04 4 views
5

Rのオブジェクトにggplotスタイルを保存する最適な方法は何ですか?私はggplotにカスタムテーマがあることを知っていますが、テーマ機能に適合しないビジュアルデザインがたくさんあります。オブジェクトにカスタムggplotスタイルを格納する

ここではいくつかのサンプルが、私は同じデザインで多くのグラフを生成し、単一のオブジェクトにデザインを保存したい、のようだ(溶融した)データと、私は

library(ggplot2) 

mdf <- structure(list(group = structure(c(2L, 3L, 1L, 2L, 3L, 1L), .Label = c("democrat", 
"founder", "libertarian"), class = "factor"), variable = structure(c(1L, 
1L, 1L, 2L, 2L, 2L), .Label = c("similar", "compete"), class = "factor"), 
    value = c(0.7, 0.2, 0.4, 0.3, 0.8, 0.6)), row.names = c(NA, 
-6L), .Names = c("group", "variable", "value"), class = "data.frame") 

ggplot(mdf, aes (x=group, y=value, fill = variable)) + 
    geom_bar(stat="identity", position="dodge", alpha = 0.8) + 
    geom_bar(stat="identity", position="dodge", color = "#A9A9A9", alpha = 0.8) + 
    scale_fill_manual(values=c("#05f2ae", "#17b0c4")) + 
    geom_text(aes(x=group, y=value, ymax=value, label=value), 
      position=position_dodge(1), vjust=-1, size=12) + 
    coord_cartesian(ylim = c(0, 1)) 
    theme(plot.margin = unit(c(1,1,2,2), "cm"), 
     axis.text.x = element_text(vjust=0.5, size=20), 
     plot.title=element_text(size=20, vjust=2), 
     panel.grid.major = element_blank(), panel.grid.minor = element_blank(), 
     axis.title.x = element_blank(), axis.title.y = element_blank(), 
     panel.background = element_rect(fill = "#D9D9D9")) 

に取り組んできたグラフです"plot_style"。これにより、後で変更する場合でも、グラフが自動的にスタイルで更新されます。

オブジェクト "x"にggplot(...)の下にすべてを格納しようとすると、エラーError: No layers in plotが発生します。単一のオブジェクトにggplotのすべての要素(変数/データを除いたもの)を格納するためのより良い方法は何ですか?

ありがとうございます。

+0

'?+ .gg'を参照してください。たとえば、基本プロットをオブジェクトに割り当て、 '%+% 'を使用して別のデータフレームでプロットを更新することができます。 – Henrik

答えて

4

カスタマイズのリストを作成し、それを各プロットに適用することができます。例:

customPlot = list(
    theme(plot.margin = unit(c(1,1,2,2), "cm"), 
     axis.text.x = element_text(vjust=0.5, size=20), 
     plot.title=element_text(size=20, vjust=2), 
     panel.grid.major = element_blank(), panel.grid.minor = element_blank(), 
     axis.title.x = element_blank(), axis.title.y = element_blank(), 
     panel.background = element_rect(fill = "#D9D9D9")), 
    coord_cartesian(ylim = c(0, 1)), 
    scale_fill_manual(values=c("#05f2ae", "#17b0c4")) 
) 

ggplot(mdf, aes (x=group, y=value, fill = variable)) + 
    geom_bar(stat="identity", position="dodge", alpha = 0.8) + 
    geom_bar(stat="identity", position="dodge", color = "#A9A9A9", alpha = 0.8) + 
    geom_text(aes(x=group, y=value, ymax=value, label=value), 
      position=position_dodge(1), vjust=-1, size=12) + 
    customPlot 
+0

素晴らしい。ちょうど私は理解しています、なぜRは未定義の値を持つリストを受け入れますが、オブジェクトとして格納されませんか?つまり、私はcustomPlotに "list()"を適用せず、代わりに< - を使用して割り当てただけではエラーになります。 – tom

+0

私は 'ggplot'が何をしているのかについての初歩的な知識しか持っていませんが、' ggplot'オブジェクトはすでにリストとして保存されていると思いますし、場合によってはリストに格納されている評価されていない式です。 – eipi10

+0

ちなみに、 'geom_bar'と' geom_text'を 'customPlot'に含めることもできます。そして、各プロットを完成させるために必要なのは' ggplot(mdf、aes(x = group、y = value、fill =変数))+ customPlot'。 – eipi10

関連する問題