簡體   English   中英

將水平分位數線添加到散點圖ggplot2 R

[英]Add horizontal quantile lines to scatter plot ggplot2 R

我下面有數據

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折線圖給出“ geom_path:每個組僅包含一個觀察值。您是否需要調整組的美觀度?”

建議將所有變量設為數字。 我的期間變量是一個字符,我想保持這種狀態,但是即使將其轉換為數字,它仍然會給我錯誤。

任何幫助,將不勝感激。 謝謝!

您想要的不是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..))

在此處輸入圖片說明

確實在哪里

quantile(eg_data$max_sales, c(0.1, 0.2))
# 10% 20% 
#   2   3 

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

我不知道這是否是最優雅的解決方案,但是您始終可以在其他地方計算匯總統計信息,然后將其放入圖表中。 這也可以更好地控制正在發生的事情(以我的口味)

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

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM