自定义轴间隔

时间:2013-10-06 19:18:49

标签: r ggplot2

我有连续的x和y值的数据。在特定的x间隔内,我想使得刻度增量更小,例如从50到60,休息之间的距离应为1(50,51,52,53 ... 59,60)。对于轴的其余部分,将刻度值增加10是可以的。我想要的x轴将在以下位置处断开:

10,20,30,40,50,51,52,53,54,55,56,57,58,58,60,70,80,90,..190,200

我尝试过:

x <- seq(1:200)
y <- seq(51, 250, by = 1)
df <- data.frame(x = x, y = y)

ggplot(data = df, aes(x, y)) +
  geom_line(size=1.6)+ 
  scale_x_continuous(breaks = c(10, 20, 30, 40, seq(50, 60, by = 2), seq(70, 200, 10)),
                     minor_breaks = seq(50, 60, by = 2)) +
theme(axis.text.x = element_text(size = 16),
      axis.text.y = element_text(size = 16),
      axis.title.x = element_text(size = 16),
      axis.title.y = element_text(size = 16),
      axis.ticks.x = element_line(size = 1),
      axis.ticks.length = unit(0.8, "cm")) + 
xlab("Time") + ylab("value")+

graph

如您所见,标签重叠。如何以更清晰的方式实现这一目标?

1 个答案:

答案 0 :(得分:23)

挤出更多的标签似乎非常紧张。所以你可以尝试通过用""

标记这四个位置,将标签放在标记52到58上。
ggplot(data = df, aes(x = x, y = y)) +
  geom_line() + 
  scale_x_continuous(breaks = c(seq(from = 10, to = 200, by = 10),
                                seq(from = 52, to = 58, by = 2)),
                     labels = c(seq(from = 10, to = 200, by = 10), rep("", 4)))

enter image description here

或者,您可以使用coord_cartesian放大相关的x范围。基础数据没有变化,我们只是放大原始数据的一小部分。然后可以将放大的绘图作为子图添加到原始绘图中。有许多方法可以安排子图。这是一个例子:

# The original plot on full range of x
g1 <- ggplot(data = df, aes(x = x, y = y)) +
  geom_line() 

# zoom in to the relevant section of x 
g2 <- ggplot(data = df, aes(x = x, y = y)) +
  geom_line() +
  coord_cartesian(xlim = c(49, 61)) +
  scale_x_continuous(breaks = seq(from = 50, to = 60, by = 2))

# print g1, and then add g2 on top using viewport from package grid
g1
print(g2, vp = viewport(x = 0.75, y = 0.3, width = 0.35, height = 0.35))

enter image description here