我有如下数据:
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)
Run Code Online (Sandbox Code Playgroud)
我想要做的,就是将第 5 对杆移到离第 4 对更远的位置。
我知道我可以通过使用这个答案来改变所有条的位置: 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()
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
36 次 |
最近记录: |