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

时间:2018-12-14 17:29:56

标签: 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函数之类的东西就可以正常工作。

summary(eg_data$max_sales)

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

  

每个组仅包含一个观察值。您是否需要调整   集体审美?

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?"

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

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

2 个答案:

答案 0 :(得分:4)

您需要的是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 

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

答案 1 :(得分:0)

我不知道这是否是最优雅的解决方案,但是您始终可以在其他地方计算汇总统计信息,然后将其放入绘图中。这也可以更好地控制正在发生的事情(以我的口味)

hline_coordinates= data.frame(Quantile_Name=names(summary(eg_data$max_sales)),
                          quantile_values=as.numeric(summary(eg_data$max_sales)))

jitter <-  (
  (ggplot(data = eg_data, aes(x=period, y=max_sales)) + #removed group=1
     geom_jitter(stat = "identity", width = .15, color = "blue", alpha = .4)) +
     scale_y_continuous(breaks= seq(0,12, by=1)) +

     geom_hline(data=hline_coordinates,aes(yintercept=quantile_values)) +
     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

enter image description here