簡體   English   中英

使用R中的ggplot2在分類散點圖中添加水平線

[英]Add horizontal lines in categorical scatter plot using ggplot2 in R

我試圖為3組繪制一個簡單的散點圖,每組有不同的水平線(線段):例如,對於組“a”,hline為3,對於組“b”,hline為2.5,hline為hline 6為組“c”。

library(ggplot2)
df <- data.frame(tt = rep(c("a","b","c"),40),
             val = round(rnorm(120, m = rep(c(4, 5, 7), each = 40))))
ggplot(df, aes(tt, val))+
geom_jitter(aes(tt, val), data = df, colour = I("red"), 
position = position_jitter(width = 0.05))

我真的很感謝你的幫助!

當一個點足夠時,永遠不要發送一條線:

library(ggplot2)

df <- data.frame(tt = rep(c("a","b","c"),40),
                 val = round(rnorm(120, m = rep(c(4, 5, 7), each = 40))))

hline <- data.frame(tt=c("a", "b", "c"), v=c(3, 2.5, 6))

ggplot(df, aes(tt, val))+
  geom_point(data=hline, aes(tt, v), shape=95, size=20) +
  geom_jitter(aes(tt, val), data = df, colour = I("red"), 
              position = position_jitter(width = 0.05))

在此輸入圖像描述

如果這是不可接受的,還有其他方法,例如:

hline <- data.frame(tt=c(1, 2, 3), v=c(3, 2.5, 6))

ggplot(df, aes(tt, val))+
  geom_jitter(aes(tt, val), data = df, colour = I("red"), 
              position = position_jitter(width = 0.05)) +
  geom_segment(data=hline, aes(x=tt-0.25, xend=tt+0.25, y=v, yend=v))

在此輸入圖像描述

這一點的缺點是嚴重的厚度和無法控制寬度。

該細分市場的缺點是需要使用數字來表示離散軸位置與因子的關系。

我也應該設置隨機種子以確保重現性。

謝謝它工作正常。 但是,當我使用氣泡圖時,第二種解決方案不起作用。

df <- data.frame(tt = rep(c("a","b","c"),40),
val = round(rnorm(120, m = rep(c(4, 5, 7), each = 40))),s=rep(c(1,10,5,50),each=30))

hline <- data.frame(tt=c(1, 2, 3), v=c(3, 2.5, 6))

ggplot(df, aes(tt, val,size=s))+

geom_jitter(aes(tt, val), data = df, colour = I("red"), 
position = position_jitter(width = 0.05))+
geom_segment(data=hline, aes(x=tt-0.25, xend=tt+0.25, y=v, yend=v))

eval中的錯誤(expr,envir,enclos):找不到對象'

暫無
暫無

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

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