Подтвердить что ты не робот

Не упускайте нулевой счет: уклонившийся барж

Я делаю уклонение barpot в ggplot2, и одна группа имеет нулевой счет, который я хочу отобразить. Я вспомнил, что видел это на ЗДЕСЬ некоторое время назад и понял, что scale_x_discrete(drop=F) будет работать. Кажется, что он не работает с уклонившимися барами. Как показать количество нулей?

Например, (код ниже) в приведенном ниже графике, type8 ~ group4 не имеет примеров. Мне все же хотелось бы, чтобы на графике отображалось пустое пространство для нулевого отсчета, а не устранение полосы. Как я могу это сделать?

enter image description here

mtcars2 <- data.frame(type=factor(mtcars$cyl), 
    group=factor(mtcars$gear))

m2 <- ggplot(mtcars2, aes(x=type , fill=group))
p2 <- m2 + geom_bar(colour="black", position="dodge") +
        scale_x_discrete(drop=F)
p2
4b9b3361

Ответ 1

Единственный способ, которым я знаю, - предварительно вычислить подсчеты и добавить фиктивную строку:

dat <- rbind(ddply(mtcars2,.(type,group),summarise,count = length(group)),c(8,4,NA))

ggplot(dat,aes(x = type,y = count,fill = group)) + 
    geom_bar(colour = "black",position = "dodge",stat = "identity")

enter image description here

Я думал, что использование stat_bin(drop = FALSE,geom = "bar",...) будет работать, но, видимо, этого не происходит.

Ответ 2

Обновлено geom_bar() требуется stat = "identity"

Для чего это стоит: таблица counts, dat, выше содержит NA. Иногда полезно иметь явное 0; например, если следующий шаг состоит в том, чтобы поместить счетчики выше баров. Следующий код делает именно это, хотя, вероятно, это не проще, чем Joran's. Он включает в себя два шага: получить перекрестную группировку счетчиков с помощью dcast, затем расплавить таблицу, используя melt, а затем ggplot(), как обычно.

library(ggplot2)
library(reshape2)
mtcars2 = data.frame(type=factor(mtcars$cyl), group=factor(mtcars$gear))

dat = dcast(mtcars2, type ~ group, fun.aggregate = length)
dat.melt = melt(dat, id.vars = "type", measure.vars = c("3", "4", "5"))
dat.melt

ggplot(dat.melt, aes(x = type,y = value, fill = variable)) + 
  geom_bar(stat = "identity", colour = "black", position = position_dodge(width = .8), width = 0.7) +
  ylim(0, 14) +
  geom_text(aes(label = value), position = position_dodge(width = .8), vjust = -0.5)

enter image description here

Ответ 3

Я задал этот же вопрос, но я хотел использовать data.table, поскольку это более быстрое решение для гораздо больших наборов данных. Я включил заметки в данные, чтобы те, кто менее опытен и хотят понять, почему я сделал то, что сделал, могут сделать это легко. Вот как я манипулировал набором данных mtcars:

library(data.table)
library(scales)
library(ggplot2)

mtcars <- data.table(mtcars)
mtcars$Cylinders <- as.factor(mtcars$cyl) # Creates new column with data from cyl called Cylinders as a factor. This allows ggplot2 to automatically use the name "Cylinders" and recognize that it a factor
mtcars$Gears <- as.factor(mtcars$gear) # Just like above, but with gears to Gears
setkey(mtcars, Cylinders, Gears) # Set key for 2 different columns
mtcars <- mtcars[CJ(unique(Cylinders), unique(Gears)), .N, allow.cartesian = TRUE] # Uses CJ to create a completed list of all unique combinations of Cylinders and Gears. Then counts how many of each combination there are and reports it in a column called "N"

И вот вызов, который создал график

ggplot(mtcars, aes(x=Cylinders, y = N, fill = Gears)) + 
               geom_bar(position="dodge", stat="identity") + 
               ylab("Count") + theme(legend.position="top") + 
               scale_x_discrete(drop = FALSE)

И он производит этот график:

Cylinder Graph

Кроме того, если есть непрерывные данные, как в наборе данных diamonds (благодаря mnel):

library(data.table)
library(scales)
library(ggplot2)

diamonds <- data.table(diamonds) # I modified the diamonds data set in order to create gaps for illustrative purposes
setkey(diamonds, color, cut) 
diamonds[J("E",c("Fair","Good")), carat := 0]
diamonds[J("G",c("Premium","Good","Fair")), carat := 0]
diamonds[J("J",c("Very Good","Fair")), carat := 0]
diamonds <- diamonds[carat != 0]

Тогда использование CJ будет работать.

data <- data.table(diamonds)[,list(mean_carat = mean(carat)), keyby = c('cut', 'color')] # This step defines our data set as the combinations of cut and color that exist and their means. However, the problem with this is that it doesn't have all combinations possible
data <- data[CJ(unique(cut),unique(color))] # This functions exactly the same way as it did in the discrete example. It creates a complete list of all possible unique combinations of cut and color
ggplot(data, aes(color, mean_carat, fill=cut)) +
             geom_bar(stat = "identity", position = "dodge") + 
             ylab("Mean Carat") + xlab("Color")

Давая нам этот график:

Diamonds Fixed

Ответ 4

Вы можете использовать функцию функции table(), которая вычисляет количество вхождений фактора для всех его уровней

# load plyr package to use ddply
library(plyr) 

# compute the counts using ddply, including zero occurrences for some factor levels
df <- ddply(mtcars2, .(group), summarise, 
 types = as.numeric(names(table(type))), 
 counts = as.numeric(table(type)))

# plot the results
ggplot(df, aes(x = types, y = counts, fill = group)) +
 geom_bar(stat='identity',colour="black", position="dodge")

График результатов