【问题标题】:decile in ggplot (geom_bar) with a fillggplot(geom_bar)中的十分位填充
【发布时间】:2017-12-27 10:56:53
【问题描述】:

我有一个包含三个变量的数据框。这是str()

'data.frame':   282 obs. of  2 variables:
 $ stars  : num  1 3 3.5 2 3.5 3 3.5 3 3.5 3.5 ...
 $ is_open: chr  "1" "0" "0" "1" ...

这是一个小例子:

structure(list(stars = c(1, 3, 3.5, 2, 3.5), is_open = c("1", 
"0", "0", "1", "1")), .Names = c("stars", "is_open"), row.names = c(NA, 
5L), class = "data.frame")

我想用变量starsggplot以十分位数的形式制作一个条形图,并填充变量is_open

但我只得到这个版本,因为我不知道如何选择 decilesis_open 变量

test %>% select(stars) %>% quantile(na.rm = T, c(0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1)) %>% barplot()

但我只得到这个结果。

使用 ggplot 无法正常工作:

ggplot(test, aes(x = stars(na.rm = T, c(0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1)), fill = is_open)) + geom_bar(stat = "identity") 

Error in stars(na.rm = T, c(0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, : 'x' must be a matrix or a data frame

知道如何通过ggplot 集成is_open 变量吗?它应该是这样的:

【问题讨论】:

  • stars() 是一个函数。那不是你想要的。最好制作你需要的data.frame,然后绘制

标签: r ggplot2 dplyr


【解决方案1】:

首先制作 data.frame(正如 Richard 建议的那样)。然后分别绘制:

library(dplyr)
library(tidyr)
library(ggplot2)

test_quant <- test %>% 
  group_by(is_open) %>% 
  do(x = seq(0, 1, 0.1),
     quant = quantile(.$stars, seq(0, 1, 0.1))) %>% 
  unnest()

ggplot(test_quant, aes(as.factor(x), quant, fill = is_open)) + 
   geom_col(position = 'dodge')

【讨论】:

    猜你喜欢
    • 2019-07-09
    • 2023-03-13
    • 2023-04-08
    • 2017-01-19
    • 2019-08-19
    • 2013-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多