[英]How to plot x-axis labels and bars between tick marks in ggplot2 bar plot?
我准備了MWE,希望對如何在成組的條形圖的x軸上的不同位置設置刻度和標簽有所幫助。
library(ggplot2)
library(reshape2)
data <- data.frame(name = c("X","Y","Z"), A = c(2,4,6), B = c(1,3,4), C = c(3,4,5))
data <- melt(data, id = 1)
ggplot(data, aes(name,value)) +
geom_bar(aes(fill = variable), position = "dodge", stat = "identity")
刻度應出現在組之間,但標簽位於組的條形下方的中心(如圖中所示)。 我試圖為scale_x_discrete
設置用戶定義的scale_x_discrete
(作為因子),但這只會使我的刻度和標簽完全消失。
任何幫助深表感謝!
一種選擇是將離散的x比例轉換為連續的,以方便計算break
位置:
# numeric version of x values
data$x <- as.integer(as.factor(data$name))
x_tick <- head(unique(data$x), -1) + 0.5
len <- length(x_tick)
ggplot(data, aes(x = x, y = value, fill = variable)) +
geom_col(position = "dodge") +
scale_x_continuous(breaks = c(sort(unique(data$x)), x_tick),
labels = c(sort(unique(data$name)), rep(c(""), len))) +
theme(axis.ticks.x = element_line(color = c(rep(NA, len + 1), rep("black", len))))
x_tick <- c(0, unique(data$x)) + 0.5
len <- length(x_tick)
ggplot(data, aes(x = x, y = value, fill = variable)) +
geom_col(position = "dodge") +
scale_x_continuous(breaks = c(sort(unique(data$x)), x_tick),
labels = c(sort(unique(data$name)), rep(c(""), len))) +
theme(axis.ticks.x = element_line(color = c(rep(NA, len - 1), rep("black", len))))
不要問我分別出現在2.25和1.75處的額外網格線...
這是另一個使用grid
包的解決方案。
library(grid)
nTicks <- 2
tickersPosition <- unit(rep(1:nTicks /(nTicks+1), each=2), "native")
第1:nTicks /(nTicks+1)
部分1:nTicks /(nTicks+1)
標識將放置刻度的位置。
p1 <- ggplot(data, aes(name,value)) +
geom_bar(aes(fill = variable), position = "dodge", stat = "identity")
要更改刻度線的位置,我們需要創建gtable
p2 <- ggplot_gtable(ggplot_build(p1))
並找到正確的grob(使用str
):
p2$grobs[[7]]$children$axis$grobs[[1]]$x <- tickersPosition
改寫職位后,我們可以運行
grid::grid.draw(p2)
這將顯示警告。 這是因為分割數不同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.