我非常感谢有关 ggplot2 问题的帮助。我一直在寻找它很长时间,所以我最好的机会现在在这里。我提供了一个可重现的脚本。
我需要做的是水平居中条形。目前,它们偏向两侧——尤其是在 2009 年和 2012 年的酒吧上。
将它们居中可以让我自由调整它们的宽度,而现在我不能。
这是当前的自包含代码:
install.packages('ggplot2')
library(ggplot2)
# Data
Year = c('2009','2009','2009','2009','2010','2010','2010','2010','2011','2011','2011','2011','2012','2012','2012','2012')
City = c('Kaunas','Vilnius','Kaunas','Vilnius','Kaunas','Vilnius','Kaunas','Vilnius',
'Kaunas','Vilnius','Kaunas','Vilnius','Kaunas','Vilnius','Kaunas','Vilnius')
Busy = c('Peak', 'Peak', 'Off-peak', 'Off-peak', 'Peak', 'Peak', 'Off-peak', 'Off-peak', 'Peak', 'Peak', 'Off-peak',
'Off-peak', 'Peak', 'Peak', 'Off-peak', 'Off-peak')
Result = c(-0.417277550641143, 0.540415934506096, -0.887323992801467, -1.0016151369497, -1.69512596882652,
-0.474180286913426, -1.87972395432173, -1.55647964460481, -1.10385766877877, -3.19261229467907,
-2.11137007243349, -3.24910554029829, -0.949278709972917, -2.22558030912235, -1.3496651478542, -2.59961942855099)
pvalue.asterisks = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, '*', NA, '*', NA, NA, NA, NA)
Results = data.frame(Year, City, Busy, Result, pvalue.asterisks)
str(Results)
Results
# Plot
ggplot(Results, aes(Year, Result, fill=City)) +
ylab(expression(paste(italic('t'), '-value'))) +
facet_grid(list('Busy', 'Year')) + scale_fill_grey(start = 0, end = .6) +
geom_bar(width=2.9, stat = "identity", position = position_dodge(width = 3)) +
scale_y_continuous(expand = c(.035,0)) + scale_x_discrete(expand = c(.7,.4)) +
theme( axis.title.x=element_blank(), axis.text.x = element_blank(),
axis.title.y = element_text(size=19, face="bold", margin = margin(0, 3, 0, 0)),
axis.text.y = element_text(size = 13),
legend.title = element_blank(), legend.text = element_text(size=17),
legend.background = element_rect(fill="white", size=0.1, linetype="solid"),
legend.key.size = unit(1.7,"line"), axis.ticks.x=element_blank(), legend.position = c(.167, .6),
panel.background = element_blank(), plot.title = element_blank(),
legend.margin=margin(c(-.05,.14,.11,.1), unit='cm'),
panel.grid.major.y = element_line(colour = "grey90"),
panel.grid.major.x = element_blank(), plot.margin = unit(c(.05, .1, 0, .1), 'cm'),
strip.text.x = element_text(face='bold', size=15, margin = margin(.2, 0, .2, 0, "cm")),
strip.text.y = element_text(face='bold', size=15, margin = margin(0, .2, 0, .2, "cm")),
strip.background = element_rect(colour="grey48", fill='grey95'), panel.spacing = unit(.08, "lines")) +
geom_text(aes(x=Year, y=Result, label=pvalue.asterisks), vjust=-.01, colour= 'white', size=15, hjust=-.168 )
- 非常感谢你