繁体   English   中英

如何限制饼图中的类别数量

[英]How to limit the number of categories in a pie chart

下面的代码通过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")

有很多方法可以解决,但基本的想法是你需要

  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进行子集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 `.( )` 

dat是我们将在ggplot使用的data.table (或data.frame

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

饼形图

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM