2017-01-27 2 views
0

Rstudioでggplotを使用して、風が特定の方向から来たときの指標の数を示す棒グラフを作成しようとしています。r ggplot出現する因子カテゴリのラベルを追加する

マイデータには、すべての方向からの風(「N」、「NE」、「E」、「SE」、「SW」、「W」、「NW」と分類されます)が含まれていません。そのような私のプロットは、彼らが特定の風向を見逃しているので、奇妙に見える。

カテゴリクラスに追加してグラフに強制的に表示する方法はありますか?

更新:dputを使用して私のデータの サブセットがある:

structure(list(Sum.of.Incidents = c(1L, 2L, 2L, 0L, 1L, 0L, 0L, 
2L, 2L, 0L, 1L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 5L, 0L, 4L, 1L, 
1L, 0L, 0L, 0L, 0L), WindDirCompass = structure(c(2L, 2L, 7L, 
8L, 6L, 5L, 2L, 1L, 1L, 2L, 8L, 8L, 7L, 3L, 7L, 1L, 8L, 6L, 6L, 
3L, 8L, 6L, 7L, 7L, 7L, 8L, 8L, 6L), .Label = c("N", "NE", "E", 
"SE", "S", "SW", "W", "NW"), class = "factor")), row.names = c(NA, 
-28L), .Names = c("Sum.of.Incidents", "WindDirCompass"), spec = structure(list(
    cols = structure(list(Sum.of.Incidents = structure(list(), class = c("collector_integer", 
    "collector")), WindDirCompass = structure(list(), class = c("collector_character", 
    "collector"))), .Names = c("Sum.of.Incidents", "WindDirCompass" 
    )), default = structure(list(), class = c("collector_guess", 
    "collector"))), .Names = c("cols", "default"), class = "col_spec"), class = c("tbl_df", 
"tbl", "data.frame")) 

私はプロットを生成するために実行しています現在のコード:

ggplot(example, aes(x = factor(WindDirCompass), 
            y = Sum.of.Incidents)) + 
    geom_bar(stat = "identity", fill = "#990033") + 
    labs(title = "", x = "Wind direction", y = "Number of incidents") + 
scale_x_discrete(drop = FALSE) 

私はまた方向で注文した:

を ​​

このように "SE"がありません。この要素を強制的に表示する方法はありますか? 私は、1つまたは2つの方向だけにインシデントがあり、風向きのほとんどが見つからない場合があります。

+1

は 'dputを使用していくつかのデータを示し、()'とすでに試みているものをご提示ください。 – Jimbou

+2

はい。 (もしあなたが[いくつかのデータとコードを追加する](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)誰かがあなたを見せてくれるかもしれない) – beetroot

答えて

1

factor()aes()から削除し、breaks

を追加したときに、希望のプロットが得られると思います factor()を使用して
ggplot(example, aes(x = WindDirCompass, 
        y = Sum.of.Incidents)) + 
    geom_bar(stat = "identity", fill = "#990033") + 
    labs(title = "", x = "Wind direction", y = "Number of incidents") + 
    scale_x_discrete(drop = FALSE, breaks = levels(example$WindDirCompass)) 

enter image description here

は、未使用のレベルが削除されるに至った:

> levels(example$WindDirCompass) 
[1] "N" "NE" "E" "SE" "S" "SW" "W" "NW" 
> levels(factor(example$WindDirCompass)) 
[1] "N" "NE" "E" "S" "SW" "W" "NW" 
0

彼らは0事件を持っているので、それだけでその要因のレベルはあなただけ追加する必要があるかもしれません、ドロップだ場合:これは問題ではない場合

ggplot(transect_weather_summary, aes(x = factor(WindDirCompass), 
           y = Sum.of.Incidents)) + 
    geom_bar(stat = "identity", fill = "#990033") + 
    labs(title = "", x = "Wind direction", y = "Number of incidents")+ 
    scale_x_discrete(drop=FALSE) 

+ scale_x_discrete(drop=FALSE)

あなたのコードでは、これがどのように見えます

+0

ありがとう。しかし、私はこれを試してみると、これらの指示のエントリーが全くないので動作しません。私はこれを空白の行として追加することでこれを強制することができますが、データを作成するよりもむしろこれを行うためのきれいな方法があることを望みました。 – cjp

関連する問題