0

以下のコードは、AlertTypeId によって円グラフを生成します。ただし、AlertTypeId が多すぎるため、円グラフのスライスの数を最も頻繁に発生する X 個のアラートに制限し、残りは「その他」のカテゴリに分類したいと考えています。どうすればggplot2でそれを行うことができますか?

a = c(0, 0, 0, 1, 2, 3, 3, 3)
b = c(1, 1, 0, 0, 1, 1, 1, 1)
c = c(1, 4, 2, 2, 2, 1, 1, 3)
sa2 = data.frame(WeekOfYear = a, UrgentState = b, AlertTypeId = c, IsUrgent = b)

ggplot(sa2, aes(x = factor(1), fill = factor(AlertTypeId))) + 
  geom_bar(width = 1) + 
  coord_polar(theta = "y")
4

1 に答える 1

2

方法はたくさんありますが、基本的な考え方は、

  1. 選択する AlertId を特定します。これには、ID ごとの行数のカウントが含まれます。
  2. ggplotプロットする行のみを含む data.frame (または data.table)に送信します。

を使用した例を次に示しdata.tableます。

編集:簡単に理解できるように、これを複数の行に分割しました

library(data.table)
sa2.DT <- data.table(sa2, key="AlertTypeId")

# we can count the rows per id, by taking the length of any other column
ATid.Counts <-  sa2.DT[, list(AT.count=length(UrgentState)), by=AlertTypeId]

# then order Id's by their counts.  We will then take the `head( )` 
#    of this vector to identify the group being kept  
ATid.Ordered <- ATid.Counts[order(AT.count, decreasing=TRUE), AlertTypeId]

ATid.Ordered頻度カウント順に並べられた Id のリストです。
取ると、それらhead(ATid.Ordered, n) のトップnの多くが得られます。
キーをsa2.DTこれらの Id として設定したので、順序付きリスト (またはその一部) を使用して、data.table

# select only those rows which have an AlertTypeId in the top n many
dat <- sa2.DT[.(head(ATid.Ordered, n=3)) ]  # <~~ note the dot in `.( )` 

datdata.table(またはdata.frame) で使用しますggplot

# use that selection to plot
ggplot(dat, aes(x = factor(1), fill = factor(AlertTypeId))) + 
  geom_bar(width = 1) + 
  coord_polar(theta = "y")

円グラフ

于 2013-04-20T15:10:10.537 に答える