我正在嘗試在 ggplot 中創建一個圖表,其中 Round1 和 Round2 之間存在分隔,同時能夠區分 Round2 中的茶點池。我正在嘗試不使用 facet wrap 或 grid do 來處理演示問題。
data.frame(Var1=c("old ","old ","old ","middle", "middle", "middle", "young", "young", "young"),
Round=c(1,2,2,1,2,2,1,2,2),
Refreshment=c(0,0,2,0,0,2,0,0,2),
Round_Refr=c(1.0,2.0,2.2,1.0,2.0,2.2,1.0,2.0,2.2),
pertotal=c(0.199, 0.196, 0.031, 0.459, 0.461, 0.020, 0.342, 0.343, 0.032))
我得到的最接近的是這個 - 但是它將每個類別(回合和年齡組作為X軸上的不同組)并在第二輪的頂部添加茶點輪,而不是將其視為它的一部分回合。
ggplot(data, aes(x = (interaction(Round,Var1)), y = pertotal))
geom_bar(aes(fill = Round_Refr),stat = "identity",color="white")
scale_y_continuous(labels=percent) xlab("category")
ylab("Percent of ") labs(fill = "Round")
ggtitle("Plot")
theme(plot.title = element_text(hjust = 0.5)

你知道一種讓它看起來更像下圖的方法嗎?他們仍然按年齡/回合分組,并且在第 2 回合的茶點池和其他受訪者之間存在界限。

uj5u.com熱心網友回復:
這是可能的,但需要一些技巧。您需要使用連續的 x 軸并將其標記為離散軸。這需要一些資料操作:
library(tidyverse)
data %>%
mutate(category = as.numeric(interaction(Round,Var1)),
category = category (category %% 2)/5 - 0.1,
Round_cat = factor(Round_Refr, labels = c("1", "2", "Break")),
Round_cat = factor(Round_cat, c("Break", "1", "2"))) %>%
group_by(Var1, Round) %>%
mutate(pertotal = ifelse(Round == 2 & Refreshment == 0,
pertotal - pertotal[Round_Refr > 2], pertotal)) %>%
ggplot(aes(x = category, y = pertotal))
geom_col(aes(fill = Round_cat), color="white")
scale_y_continuous(labels=scales::percent)
scale_x_continuous(breaks = c(1.5, 3.5, 5.5),
labels = levels(factor(data$Var1)))
xlab("category")
ylab("Percent of ")
labs(fill = "Round")
ggtitle("Plot")
scale_fill_brewer(palette = "Set1")
theme_light(base_size = 16)
theme(plot.title = element_text(hjust = 0.5))

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/477208.html
