13

私はRの初心者なので、私の無知を許してください。geom_bar を使用して 4 セットのバーを重ね合わせた疑似スタック バープロットを作成しました。3 種類のオークの木 (QUAG、QUKE、QUCH) には、4 つの健康状態カテゴリ (生存、死亡、感染、および枯死) があります。

私のコードは次のとおりです。


x <- as.data.frame(list(variable=c("QUAG", "QUKE", "QUCH"), alive = c(627,208,109),  infected = c(102,27,0), dead = c(133,112,12), sod.dead=c(49,8,0)))

x.plot = ggplot(x, aes(variable, alive)) + geom_bar(fill="gray85") + 
  geom_bar(aes(variable,dead), fill="gray65") +
  geom_bar(aes(variable, infected), fill="gray38") +
  geom_bar(aes(variable, sod.dead), fill="black")+
  opts(panel.background = theme_rect(fill='gray100'))
x.plot

ここで、どの灰色の色合いが木の状態に関連するかを示す凡例を作成したいと思います。つまり、「gray65」は「枯れ木」などです。過去1時間試してみましたが、機能しません。

4

2 に答える 2

10

@Brandon Bertelsen が素晴らしい回答を投稿したようです。元の投稿に記載されている追加の詳細に対応するコードをいくつか追加したいと思います。

  1. データを再形成し、ヘルス ステータスを にマップするとfill、ggplot によって凡例が自動的に作成されます。
  2. scale_fill_manual()元の投稿に記載されている正確なグレーを取得するために使用することをお勧めします。
  3. theme_bw()は、プロットを白黒ですばやく表示するための便利な関数です。
  4. 因子レベル/色のプロット順序は、levels引数 で目的の順序を指定することによって制御できますfactor()
  5. このデータ セットには、(積み上げではなく) 覆い隠された棒グラフを使用すると、いくつかの利点がある場合があります。

library(reshape2)
library(ggplot2)

x <- as.data.frame(list(variable=c("QUAG", "QUKE", "QUCH"), 
                        alive=c(627, 208, 109),  infected=c(102, 27, 0), 
                        dead=c(133, 112, 12), sod.dead=c(49, 8, 0)))

# Put data into 'long form' with melt from the reshape2 package.
dat = melt(x, id.var="variable", variable.name="status")

head(dat)
#    variable   status value
# 1      QUAG    alive   627
# 2      QUKE    alive   208
# 3      QUCH    alive   109
# 4      QUAG infected   102
# 5      QUKE infected    27
# 6      QUCH infected     0

# By manually specifying the levels in the factor, you can control
# the stacking order of the associated fill colors.
dat$status = factor(as.character(dat$status), 
                    levels=c("sod.dead", "dead", "infected", "alive"))

# Create a named character vector that relates factor levels to colors.
grays = c(alive="gray85", dead="gray65", infected="gray38", sod.dead="black")

plot_1 = ggplot(dat, aes(x=variable, y=value, fill=status)) +
         theme_bw() +
         geom_bar(position="stack") +
         scale_fill_manual(values=grays)

ggsave(plot=plot_1, filename="plot_1.png", height=5, width=5)

ここに画像の説明を入力

# You may also want to try a dodged barplot.
plot_2 = ggplot(dat, aes(x=variable, y=value, fill=status)) +
         theme_bw() +
         geom_bar(position="dodge") +
         scale_fill_manual(values=grays)

ggsave(plot=plot_2, filename="plot_2.png", height=4, width=5)

ここに画像の説明を入力

于 2012-11-13T03:02:14.050 に答える
2

データの形を変える必要があります。

library(reshape)
library(ggplot2)

x <- as.data.frame(list(variable=c("QUAG", "QUKE", "QUCH"), alive = c(627,208,109),  infected = c(102,27,0), dead = c(133,112,12), sod.dead=c(49,8,0)))

x <- melt(x)
colnames(x) <- c("Type","Status","value")

ggplot(x, aes(Type, value, fill=Status)) + geom_bar(position="stack")
于 2012-11-13T00:50:42.393 に答える