Joh*_*nna 8 r ggplot2 axis-labels
我准备了一个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")
Run Code Online (Sandbox Code Playgroud)

刻度应显示在组之间,但标签位于分组条形下方(如图中所示).我尝试设置用户定义的中断(作为因子),scale_x_discrete但它只使我的刻度和标签完全消失.
任何帮助深表感谢!
一种选择是将离散x标度转换为连续标度,以便于计算break位置:
# numeric version of x values
data$x <- as.integer(as.factor(data$name))
Run Code Online (Sandbox Code Playgroud)
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))))
Run Code Online (Sandbox Code Playgroud)
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))))
Run Code Online (Sandbox Code Playgroud)
不要问我有关分别出现在2.25和1.75的额外网格线...
| 归档时间: |
|
| 查看次数: |
3256 次 |
| 最近记录: |