這是一個虛擬代碼:
library(ggplot2)
library(dplyr)
diamonds |> dplyr::filter(color %in% c("D","E", "F"), cut %in% c("Ideal","Fair"), clarity %in% c("SI2","VS2","IF")) |> ggplot(aes(x = clarity, y =carat, color=color, shape=cut))
stat_summary(fun.data= mean_cl_boot, geom="errorbar", width=0.05, position=position_dodge(0.7))
stat_summary(fun=mean, geom="point", size=2, position= position_dodge(0.7))
我想在每個凈度類別中將方法與一條線連接起來(即將圓圈連接到三角形:以圖片中的紅色顯示為例):

如果我使用geom_stator : 它會給出一個 有意義geom_line的錯誤,因為它們都在一個組中。我嘗試使用但它也不起作用,我只能針對不同組內的點進行操作geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?claritygroup=interaction()clarity
uj5u.com熱心網友回復:
我認為最好使用手動閃避
library(ggplot2)
library(dplyr)
df <- diamonds %>% dplyr::filter(color %in% c("D","E", "F"), cut %in% c("Ideal","Fair"), clarity %in% c("SI2","VS2","IF"))
## make a names vector for your manual dodge
## this of course needs adjustment depending on your actual data. can be automated
dodge_vec <- seq(-.25, .25, length = 6)
names(dodge_vec) <- unique(with(df, paste(cut, color, sep = "_")))
## some data alterations - assign dodge by subsetting with named vector
df <- df %>%
mutate(cut_col = dodge_vec[paste(cut, color, sep = "_")])
## summarise for your lines
df_line <-
df %>%
group_by(clarity, cut, color, cut_col) %>%
summarise(mean_carat = mean(carat))
#> `summarise()` has grouped output by 'clarity', 'cut', 'color'. You can override
#> using the `.groups` argument.
## need to pass your original x as an integer and add your new doding column
ggplot(df, aes(x = as.integer(factor(clarity)) cut_col, y =carat, color=color, shape=cut))
stat_summary(fun.data= mean_cl_boot, geom="errorbar", width=0.05)
stat_summary(fun=mean, geom="point", size=2)
## add lines with your new data, using an interaction variable
geom_line(data = df_line, aes(y = mean_carat, group = interaction( as.integer(clarity), color)))
scale_x_continuous(breaks = 1:3, labels = unique(df$clarity))
#> Warning: Using shapes for an ordinal variable is not advised

您的問題表明您正在處理配對資料,因此我在評論中提出了建議。我想舉個例子,但是鉆石資料集沒有配對資料,因此偽造它有點困難。
由reprex 包于 2022-05-31 創建(v2.0.1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/483762.html
上一篇:線型中沒有重疊的條形圖
