[英]How can I add custom ticks and text to ggplot2 x-axis
I am trying to add custom ticks to a geom_col
figure but have not been able to figure it out.我正在尝试将自定义刻度添加到
geom_col
图形,但无法弄清楚。 I would like for the x-axis to display both the individual siteID
and below that the grouping Region
ID (multiple sites can belong to one region).我希望 x 轴同时显示单个
siteID
ID,并在其下方显示分组Region
ID(多个站点可以属于一个区域)。 Below is a reprex example of what I'm trying to do (please no annoying comments like "YoU sHoUlDn'T uSe GeOm_CoL tO dIsPlAy MeAnS").下面是我正在尝试做的一个代表示例(请不要出现烦人的评论,例如“你不应该使用 GeOm_CoL 来处理”)。
Example below is as far as I have gotten:下面的例子是据我所知:
library(data.table)
library(dplyr)
df1 <- data.frame(matrix(ncol = 3, nrow = 18))
x <- c("siteID", "Region", "Wtemp")
colnames(df1) <- x
df1$siteID <- c("ace","ace","ace",
"hud","hud","hud","hud",
"apa","apa","apa","apa","apa",
"cbv","cbv","cbv","cbv","cbv","cbv")
df1$Region <- c("North","North","North",
"North","North","North","North",
"South","South","South","South","South",
"East","East","East","East","East","East")
set.seed(55)
df1$Wtemp <- rnorm(18,20,10)
test_table <- df1 %>%
group_by(siteID, Region) %>%
summarise(MeanWtemp = mean(Wtemp))
test_table %>%
arrange(-desc(Region)) %>%
mutate(siteID = factor(siteID, levels = c("cbv","ace","hud","apa"))) %>%
ggplot(aes(x = siteID, y = MeanWtemp)) +
geom_col(color = "black") +
labs(x = "Site & Region",
y = "Mean Water Temp. (C)") +
theme_bw() +
theme(plot.margin = margin(5,5,50,5,"pt"),,
panel.grid = element_blank(),
text = element_text(size = 14),
axis.text.x = element_text(size = 14, color = "black"),
axis.text.y = element_text(size = 14, color = "black"),
axis.title.x = element_text(vjust = -15))
The figure should look something like this picture below where the x-axis has custom ticks at certain positions and of certain lengths along with custom text specifying Region
.该图应类似于下图,其中 x 轴在特定位置和特定长度具有自定义刻度以及指定
Region
的自定义文本。
I don't think there's a built-in way to do this, but you can fake it thusly.我认为没有内置的方法可以做到这一点,但你可以这样伪造它。
clip = "off"
in coord_cartesian
lets us plot outside the plot range, and specifying ylim
makes it so the y axis is not expanded to accommodate the annotations within their range. coord_cartesian
中的clip = "off"
让我们 plot 超出 plot 范围,并指定ylim
使其不会扩展 y 轴以容纳其范围内的注释。 The annotation positions are customized to this data, but with some planning you could probably come up with a procedure to generate it automatically.注释位置是根据这些数据定制的,但是通过一些计划,您可能会想出一个自动生成它的过程。
#...your code
coord_cartesian(clip = "off", ylim = c(0, NA)) +
annotate("text", x = c(1, 2.5, 4), y = -4, label = c("East", "North", "South"), size = 5) +
annotate("segment", x = c(1.5, 3.5), xend = c(1.5, 3.5), y = -1, yend = -5) +
#... the rest of your code
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.