gpt4 book ai didi

r - 将最后一对列从 ggplot2 中的其他列移开

转载 作者:行者123 更新时间:2023-12-05 09:32:03 25 4
gpt4 key购买 nike

我有如下数据:

library(data.table)
library(ggplot2)
library(dplyr)
library(tidyverse)
library(ggsignif)

graph <- structure(list(Constraint = structure(c(4L, 2L, 3L, 1L, 5L, 4L,
2L, 3L, 1L, 5L), .Label = c("Major Constraint", "Minor Constraint",
"Moderate Constraint", "No Constraint", "Total"), class = "factor"),
`Observation for Crime = 0` = c(3124, 2484, 3511, 4646, 13765,
3124, 2484, 3511, 4646, 13765), `Observation for Crime = 1` = c(762,
629, 1118, 1677, 4186, 762, 629, 1118, 1677, 4186), `Total Observations` = c(3886,
3113, 4629, 6323, 17951, 3886, 3113, 4629, 6323, 17951),
variable = structure(c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L,
2L), .Label = c("Crime = 0", "Crime = 1"), class = "factor"),
value = c(80.3911477097272, 79.79441053646, 75.847915316483,
73.4777795350308, 76.6809648487549, 19.6088522902728, 20.20558946354,
24.152084683517, 26.5222204649692, 23.3190351512451)), row.names = c(NA,
-10L), class = "data.frame")
setnames(graph, "variable", "Crime Incidence (Yes=1)")


graph %>%
mutate(`Constraint` = fct_relevel(`Constraint`, "No Constraint", "Minor Constraint", "Moderate Constraint", "Major Constraint")) %>%
ggplot(aes(x = `Constraint`, y = value)) +
geom_col(position = 'dodge', aes(fill = `Crime Incidence (Yes=1)`)) +
geom_text(position = position_dodge(width = .9), # move to center of bars
aes(label=sprintf("%.02f %%", round(value, digits = 1)), group = `Crime Incidence (Yes=1)`),
vjust = -2.5, # nudge above top of bar
size = 4) +
geom_text(position = position_dodge(width = .9), # move to center of bars
aes(label= paste0("(", ifelse(`Crime Incidence (Yes=1)` == "Crime = 0", `Observation for Crime = 0`, `Observation for Crime = 1`), ")"), group = `Crime Incidence (Yes=1)`),
vjust = -0.6, # nudge above top of bar
size = 4) +
scale_fill_grey(start = 0.8, end = 0.5) +
ylab("% within constraint level (Observations in parentheses)") +
xlab("Perception of Taxes as a Constraint") +
scale_y_continuous(expand = expansion(mult = c(0, .1))) +
theme_bw(base_size = 15)

enter image description here

我想做的是简单地将第 5 对条形图移动到远离第 4 对条形图。

我知道我可以使用 this answer 更改所有条形图的位置: position = position_dodge(width=0.5),但这适用于所有列对。我希望它只适用于最后一对。

最佳答案

如果您真的想这样做(我不建议这样做),您可以将 x 变量设为一个因子并将水平设置为包括空白观察;添加该级别的空白观察;和情节。

例如:

library(ggplot2)
library(dplyr)

dat <- iris

dat <- iris %>%
mutate(Species = factor(Species, levels = c(
# all except last level
levels(iris$Species)[1:length(levels(iris$Species))-1],
# blank (empty) factor level
" ",
# final level
levels(iris$Species)[length(levels(iris$Species))]
))) %>%
add_row(Species = factor(" "))

dat %>%
ggplot(aes(x = Species, y = Sepal.Length)) +
geom_col()

plot

关于r - 将最后一对列从 ggplot2 中的其他列移开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68405889/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com