-3

R に問題があります。ここで何かが間違っているはずです。2 つの異なる変数の凡例を追加したいと思います。1 つは赤色の「Insgesamt_ALL」で、もう 1 つは黒色の「weiblich_ALL」です。

> data<-read.csv("DatensatzUE4_01.csv",sep=";",header=T)

> nDATA<-subset(data,data$Fach=='Wirtschaftsingenieurw.m.wirtschaftswiss.Schwerpkt.')
> 
> library(ggplot2)
> 
> p <- ggplot(data=nDATA,aes(x=Semester,fill=y))
+     ggtitle("GGplot")
+     xlab("Year and Semester")
+     ylab("Total of the student")
+     geom_bar(size=3,aes(y=Insgesamt_ALL,fill=Semester),stat="identity",fill="red")
+     geom_bar(size=3,aes(y=weiblich_ALL,fill=Semester),stat="identity",fill="black")
> 
> p2<-p+ 
    theme(panel.background=element_rect(fill="white"),
          panel.grid.major=element_line(colour="grey",size=0.1),
          plot.title=element_text(face="bold"),
          axis.text=element_text(colour="black"),
          axis.title.x=element_text(face="bold"),
           axis.text.x=element_text(angle=90) )
> 
> plot(p2)

結果:

ここに画像の説明を入力

4

1 に答える 1

1

凡例の欠落に関する基本的な問題は、変数にマッピングして ggplot 塗りつぶしの美学を利用する必要があることです。その後、必要に応じて塗りつぶしの色を変更できます。と の2 つの変数がInsgesamt_ALLありweiblich_ALLます。

まず、実際のデータセットを模倣するいくつかの偽のデータ (@jlhoward のコメントを参照) を作成しましょう。

(tmp_data <- data.frame(Semester = seq(1:12), Insgesamt_ALL = sample(0:3000, 12),     weiblich_ALL = sample(2000:5000, 12)))

   Semester Insgesamt_ALL weiblich_ALL
1         1          2264         2643
2         2           244         3742
3         3          1681         2897
4         4          1037         4342
5         5          1225         4384
6         6           478         2195
7         7            97         2948
8         8          2537         3509
9         9          1210         3892
10       10          2016         2507
11       11          2524         2415
12       12           427         4167

最初の重要なポイントは、一連のキー/値の観測を ggplot にフィードする必要があることです。そのため、データセットを再形成しましょう。

library(tidyr)
nDATA    <- gather(tmp_data, variable, count_of_student, Insgesamt_ALL, weiblich_ALL)

ここでは使用tidyr::gatherしましたが、他のツールでも問題ありません。すぐにプロットしましょう:

library(ggplot2)
p <- ggplot(nDATA) + geom_bar(aes(x = Semester, y = count_of_student, fill = variable), stat = "identity")
plot(p)

ここに画像の説明を入力

あなたがしたいことは、基本的に塗りつぶしスケールをカスタムカラー(黒と赤)に変更することです:

fill_colors        <- c("#000000", "#FF0000")
names(fill_colors) <- levels(nDATA$variable)
fill_scale <- scale_fill_manual(name = "Variable", values = fill_colors)

p + fill_scale

ここに画像の説明を入力

variable最後に、因子のレベルを並べ替えて、黒と赤の塗りつぶしの色を切り替えましょう。

nDATA$variable         <- relevel(nDATA$variable, ref = "weiblich_ALL")
new_fill_colors        <- fill_colors
names(new_fill_colors) <- levels(nDATA$variable)
new_fill_scale <- scale_fill_manual(name = "Variable", values = new_fill_colors)
p + new_fill_scale

ここに画像の説明を入力

あなたは今、正しい軌道に乗っているはずです。

于 2014-12-24T09:37:07.870 に答える