如何在ggplot2条形图中的刻度线之间绘制x轴标签和条形图? [英] How to plot x-axis labels and bars between tick marks in ggplot2 bar plot?

查看:321
本文介绍了如何在ggplot2条形图中的刻度线之间绘制x轴标签和条形图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我准备了MWE,希望对如何在成组的条形图的x轴上的不同位置设置刻度和标签有所帮助.

I prepared a MWE and hope for help on how to set ticks and labels at different position on the x-axis for a grouped bar plot.

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设置用户定义的间隔(作为因素),但这只会使我的刻度和标签完全消失.

The ticks should appear BETWEEN the groups, but the labels centered below the grouped bars (as they are in the figure). I tried to set user-defined breaks (as factors) for scale_x_discrete but it only made my ticks and labels disappear completely.

非常感谢您的帮助!

推荐答案

一种选择是将离散的x比例转换为连续的,以方便计算break位置:

One options would be to convert the discrete x scale to continuous, to facilitate calculation of break positions:

# numeric version of x values
data$x <- as.integer(as.factor(data$name))

1.条形组之间的x滴答声

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处的额外网格线...

Don't ask me about the additional grid lines which appeared at 2.25 and 1.75 respectively...

这篇关于如何在ggplot2条形图中的刻度线之间绘制x轴标签和条形图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆