r - 将水平分位数线添加到散点图 ggplot2 R

标签 r ggplot2 scatter-plot quartile

我有下面的数据

eg_data <- data.frame(
period = c(sample( c("1 + 2"), 1000, replace = TRUE)),
max_sales = c(sample( c(1:10), 1000, replace = TRUE, prob = 
c(.05, .10, .15, .25, .25, .10, .05, .02, .02, .01)))

我想制作一个 scatter (实际上是 jitter )图并在沿 y 轴的不同点添加水平线。我希望能够自定义添加行的百分位数,但就目前而言,R 的汇总函数之类的东西可以正常工作。
summary(eg_data$max_sales)

我有下面的抖动图代码。它运行并生成图形,但我不断收到错误消息:

Each group consists of only one observation. Do you need to adjust the group aesthetic?


jitter <-  (
(ggplot(data = eg_data, aes(x=period, y=max_sales, group = 1)) +
geom_jitter(stat = "identity", width = .15, color = "blue", alpha = .4)) +
scale_y_continuous(breaks= seq(0,12, by=1)) +
geom_line(stat = 'summary', fun.y = "quantile", fun.args=list(probs=0.1)) +
ggtitle("Distribution of Sales by Period") + xlab("Period") + ylab("Sales") +
theme(plot.title = element_text(color = "black", size = 14, face = "bold", hjust = 0.5),
      axis.title.x = element_text(color = "black", size = 12, face = "bold"), 
      axis.title.y = element_text(color = "black", size = 12, face = "bold")) +
labs(fill = "Period") )
jitter

我试着看这个问题 -

ggplot2 line chart gives "geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?"

它建议将所有变量设为数字。我的期间变量是一个字符,我想保持这种方式,但即使我将其转换为数字,它仍然给我错误。

任何帮助,将不胜感激。谢谢!

最佳答案

你想要的是 geom_line 而不是 geom_hline 。特别是,将 geom_line 替换为

stat_summary(fun.y = "quantile", fun.args = list(probs = c(0.1, 0.2)), 
             geom = "hline", aes(yintercept = ..y..))



enter image description here

确实在哪里
quantile(eg_data$max_sales, c(0.1, 0.2))
# 10% 20% 
#   2   3 

它还消除了您收到的警告。

关于r - 将水平分位数线添加到散点图 ggplot2 R,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53784381/

相关文章:

r - data.table:从值中减去水平意味着

r - 使用 CSS 和 Quarto/reveal.js 更改幻灯片背景

r - 如何在 ggplot2 中仅使用一个命令来增加点和文本的大小?

r - 如何使用 ggplot2 可视化钻孔剖面(堆积条形图)?

python - 在 Python basemap 上重绘绘图

r - 如何让 lm 忽略 NA 列

r - 具有置信区间的交互图

r - 按组对 df 进行子集化,遍历散点图

python - 如何使用 seaborn 创建具有连接点的多个系列散点图?

r - 在矩阵列表上简化应用、应用表达式